4

I have a string and I need to replace all the ' and etc to their proper value

I am using

var replace = str.replace(new RegExp("[']", "g"), "'");

To do so, but the problem is it seems to be replacing ' for each character (so for example, ' becomes '''''

Any help?

Steven
  • 13,250
  • 33
  • 95
  • 147
  • The error is in the use of `[]`. If you remove them it should work. Or use the more compact JS notation as suggested by arnaud. – xanatos Sep 11 '11 at 19:43

3 Answers3

10

Use this:

var str = str.replace(/'/g, "'");

['] is a character class. It means any of the characters inside of the braces.

This is why your /[']/ regex replaces every single char of ' by the replacement string.


If you want to use new RegExp instead of a regex literal:

var str = str.replace(new RegExp(''', 'g'), "'");

This has no benefit, except if you want to generate regexps at runtime.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
6

Take out the brackets, which makes a character class (any characters inside it match):

var replace = str.replace(new RegExp("'", "g"), "'");

or even better, use a literal:

var replace = str.replace(/'/g, "'");

Edit: See this question on how to escape HTML: How to unescape html in javascript?

Community
  • 1
  • 1
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
2

Rather than using a bunch of regex replaces for this, I would do something like this and let the browser take care of the decoding for you:

    function HtmlDecode(s) {
        var el = document.createElement("div");
        el.innerHTML = s;
        return el.innerText || el.textContent;
    }
nw.
  • 4,795
  • 8
  • 37
  • 42
  • 1
    +1 Good idea... though you don't need to call `delete el;` (it has no effect and even throws an error in strict mode). You could just do `return el.innerText || el.textContent;` – Felix Kling Sep 11 '11 at 20:03