最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript find and replace a set of characters? - Stack Overflow

programmeradmin7浏览0评论

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, ' bees '''''

Any help?

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, ' bees '''''

Any help?

Share Improve this question asked Sep 11, 2011 at 19:41 StevenSteven 14k34 gold badges102 silver badges155 bronze badges 1
  • The error is in the use of []. If you remove them it should work. Or use the more pact JS notation as suggested by arnaud. – xanatos Commented Sep 11, 2011 at 19:43
Add a ment  | 

3 Answers 3

Reset to default 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.

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?

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;
    }
发布评论

评论列表(0)

  1. 暂无评论