javascript 如何创建字符串“全部替换”函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9641481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:19:14  来源:igfitidea点击:

How to create a string "replace all" function?

javascript

提问by mpen

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 yourvarmay contain special characters, and I don't want it to be treated like a regex.

但我想用一个变量代替“你的字符串”。然后人们说,只需使用new RegExp(yourvar, 'g'). 问题在于它yourvar可能包含特殊字符,我不希望它被视为正则表达式。

So how do we do this properly?

那么我们如何正确地做到这一点呢?



Example input:

示例输入:

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

Desired output:

期望的输出:

'axbx'

回答by Marshall

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";

回答by Felipe

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

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

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

回答by diaho

you can escape your yourvarvariable using the following method:

您可以yourvar使用以下方法转义变量:

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

回答by Shawn Allen

XRegExpprovides a function for escaping regular expression characters in strings:

XRegExp提供了一个函数来转义字符串中的正则表达式字符:

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

回答by mpen

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

解决方案2

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


jsPerf Test

jsPerf 测试