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

javascript - How to create a string "replace all" function? - Stack Overflow

programmeradmin2浏览0评论

Every article or question I've seen pretty much says, just use:

str.replace(/yourstring/g, 'whatever');

But I want to use a variable in place of "yourstring". Then people say, just use new RegExp(yourvar, 'g'). The problem with that is that yourvar may contain special characters, and I don't want it to be treated like a regex.

So how do we do this properly?


Example input:

'a.b.'.replaceAll('.','x')

Desired output:

'axbx'

Every article or question I've seen pretty much says, just use:

str.replace(/yourstring/g, 'whatever');

But I want to use a variable in place of "yourstring". Then people say, just use new RegExp(yourvar, 'g'). The problem with that is that yourvar may contain special characters, and I don't want it to be treated like a regex.

So how do we do this properly?


Example input:

'a.b.'.replaceAll('.','x')

Desired output:

'axbx'
Share Improve this question edited Aug 17, 2015 at 20:52 mpen asked Mar 9, 2012 at 21:51 mpenmpen 283k281 gold badges889 silver badges1.3k bronze badges 3
  • You want to not treat regex like regex? Can you define the types of input you'd like to provide? Will you want regex-functionality, or is it just a string of literal characters, "ABc34*\d/4h" you want to work with/replace? – David Thomas Commented Mar 9, 2012 at 21:53
  • @DavidThomas: Any input. All I want is a simple function that replaces all instances of "x" with "y", not just the first one, as string.replace does. – mpen Commented Mar 9, 2012 at 21:59
  • 1 'a.b.c'.split('.').join('x') – david Commented Mar 9, 2012 at 22:14
Add a comment  | 

5 Answers 5

Reset to default 9

You can split and join.

var str = "this is a string this is a string this is a string";

str = str.split('this').join('that');

str; // "that is a string that is a string that is a string";

From http://cwestblog.com/2011/07/25/javascript-string-prototype-replaceall/

String.prototype.replaceAll = function(target, replacement) {
  return this.split(target).join(replacement);
};

you can escape your yourvar variable using the following method:

function escapeRegExp(text) {
    return text.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

XRegExp provides a function for escaping regular expression characters in strings:

var input = "$yourstring!";
var pattern = new RegExp(XRegExp.escape(input), "g");
console.log("This is $yourstring!".replace(pattern, "whatever"));
// logs "This is whatever"

Solution 1

RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

String.prototype.replaceAll = function(search, replace) {
    return this.replace(new RegExp(RegExp.escape(search),'g'), replace);
};

Solution 2

'a.b.c.'.split('.').join('x');

jsPerf Test

发布评论

评论列表(0)

  1. 暂无评论