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?

user2428118
  • 7,935
  • 4
  • 45
  • 72
Vaandu
  • 4,857
  • 12
  • 49
  • 75

2 Answers2

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 & ' \""
Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
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, "\""));
gen_Eric
  • 223,194
  • 41
  • 299
  • 337