Reputation: 4945
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?
Upvotes: 1
Views: 937
Reputation: 76413
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).
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 & ' \""
Upvotes: 3
Reputation: 227280
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, "\""));
Upvotes: 2