1

I'm trying to replace some codes in JavaScript. Somehow, this doesn't work.

var name = "check & ' \"";
alert(name);
alert(name.replace(/["]/g, "\""));
alert(name.replace(/[\]/g, "\"));       

What am I doing wrong?

1
  • Those "codes" are called entities, by the way. Commented Oct 6, 2012 at 14:50

2 Answers 2

3

Don't use regex, just parse it:

 var d = document.createElement('div');
 d.innerHTML = "check & ' \"";
 console.log(d.innerText);//all done

Create an element (in memory, it won't show), and use the innerText property, this'll return the text equivalent (ie converts all html-entities to their respective chars).

read this

As a side-note: the reason why /["]/g would never work is because you're creating a character class/group: it'll match any 1 character of the group, not the entire string:

d.innerHTML.replace(/["]/g,'@');//"check @amp@ ' \""
d.innerHTML.replace(/(")/g,'@');//"check & ' \""
Sign up to request clarification or add additional context in comments.

2 Comments

@DavidThomas: NP, you were right. I had no reason to be blunt
Meh, we've all been there... =)
2

In regex, [] means "any of the following characters". So, /[\]/g will match a &, a #, a 9, a 2 or a ;.

Try it without the [].

var name = "check & ' \"";
alert(name);
alert(name.replace(/"/g, "\""));
alert(name.replace(/\/g, "\""));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.