如何替换JavaScript中出现的所有字符串?

时间:2022-10-05 19:19:06

I have this string:

我有这个字符串:

"Test abc test test abc test test test abc test test abc"

Doing

str = str.replace('abc', '');

seems to only remove the first occurrence of abc in the string above. How can I replace all occurrences of it?

似乎只删除上面字符串中abc的第一次出现。如何替换它的所有出现?

41 个解决方案

#1


1558  

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

为了完整性起见,我考虑了应该使用哪种方法来实现这一点。在这一页上,有两种方法可以解决这个问题。

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.

注意:通常不推荐在JavaScript中扩展内置原型。我在String原型上提供的扩展只是为了说明,在String内置原型上显示了一个假想的标准方法的不同实现。


Regular Expression Based Implementation

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

Split and Join (Functional) Implementation

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

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

由于不太了解正则表达式在幕后如何高效地工作,我过去倾向于使用分割和加入实现,而不考虑性能。当我真的想知道哪一种更有效,用什么优势,我就以此为借口找出答案。

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

在我的Chrome Windows 8机器上,基于正则表达式的实现速度最快,分割和连接实现速度慢53%。这意味着我使用的lorem ipsum输入的正则表达式速度是原来的两倍。

Check out this benchmark running these two implementations against each other.

检查一下运行这两个实现的基准。


As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

正如@ThomasLeduc和其他人在下面的评论中所指出的,如果搜索包含正则表达式中作为特殊字符保留的某些字符,那么基于正则表达式的实现可能会有问题。实现假定调用者将事先转义字符串,或者只传递正则表达式(MDN)中表中没有字符的字符串。

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

MDN还提供了一个实现来转义我们的字符串。如果它也被标准化为regexpe .escape(str),那就太好了,但可惜它并不存在:

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

我们可以在string。prototype中调用escapeRegExp。然而,replaceAll实现并不确定这会对性能产生多大影响(甚至可能对不需要转义的字符串,比如所有的字母数字字符串)。

#2


3529  

str = str.replace(/abc/g, '');

In response to comment:

在回应评论:

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

作为对Upvote评论的回应,您可以进一步简化它:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function:

注意:正则表达式包含特殊的(元)字符,因此,在上面的find函数中盲目地传递一个参数而不进行预处理以转义这些字符是危险的。这在Mozilla开发人员网络关于正则表达式的JavaScript指南中有所介绍,其中介绍了以下实用功能:

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

因此,为了使上面的replaceAll()函数更安全,如果还包括escapeRegExp,可以将其修改为如下:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

#3


1185  

Note: Don't use this in real code.

注意:不要在真正的代码中使用它。

As an alternative to regular expressions for a simple literal string, you could use

作为对简单文字字符串的正则表达式的替代,您可以使用

str = "Test abc test test abc test...".split("abc").join("");

The general pattern is

一般的模式是

str.split(search).join(replacement)

This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.

在某些情况下,这比使用replaceAll和正则表达式要快,但在现代浏览器中似乎不再如此。因此,这应该只是作为一种快速的技巧来使用,以避免需要转义正则表达式,而不是在真正的代码中。

#4


493  

Using a regular expression with the g flag set will replace all:

使用带有g标志集的正则表达式将替换所有:

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

See here also

#5


90  

Here's a string prototype function based on the accepted answer:

下面是一个基于公认答案的字符串原型函数:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find, 'g'), replace);
};

EDIT

编辑

If your find will contain special characters then you need to escape them:

如果你的发现将包含特殊字符,那么你需要转义它们:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};

Fiddle: http://jsfiddle.net/cdbzL/

小提琴:http://jsfiddle.net/cdbzL/

#6


75  

Update:

更新:

It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b)

更新有点晚了,但是因为我刚刚遇到这个问题,并且注意到我之前的答案不是我喜欢的。因为这个问题涉及替换一个单词,所以没有人想到使用单词边界(只\b)

'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"

This is a simple regex that avoids replacing parts of words in most cases. However, a dash - is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat:

这是一个简单的正则表达式,避免在大多数情况下替换部分单词。然而,破折号仍然被认为是一个词的边界。所以在这种情况下,条件句可以用来避免替换像cool-cat这样的字符串:

'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"

basically, this question is the same as the question here: Javascript replace " ' " with " '' "

基本上,这个问题和这里的问题是一样的:用Javascript代替" ' "

@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!

@Mike,看看我给出的答案……regexp并不是唯一的方法来替换多次出现的subsrting,远非如此。灵活,认为分裂!

var newText = "the cat looks like a cat".split('cat').join('dog');

Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:

另外,为了防止替换单词部件——批准的答案也可以!您可以使用正则表达式来解决这个问题,我承认,这些表达式有些复杂,因此也会稍微慢一点:

var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");

The output is the same as the accepted answer, however, using the /cat/g expression on this string:

但是,使用该字符串上的/cat/g表达式,输出与已接受的答案相同:

var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ?? 

Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:

糟糕,这可能不是你想要的。那么,是什么呢?IMHO是一个正则表达式,只在条件下替换“cat”。像这样:

var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"

My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.

我的猜测是,这符合你的需要。当然,这并不是充分的证明,但它应该足以让你开始。我建议多读一些这几页。这将证明在完善这个表达式以满足您的特定需求时是有用的。

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.regular-expressions.info

http://www.regular-expressions.info


Final addition:

最后补充:

Given that this question still gets a lot of views, I thought I might add an example of .replace used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat and cats in one go:

考虑到这个问题仍然有很多视图,我想我可以添加一个.replace示例,使用回调函数。在这种情况下,它极大地简化了表达式,并提供了更大的灵活性,比如用正确的大小写替换,或者一次替换猫和猫:

'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
   .replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
    {
       //check 1st, capitalize if required
       var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
       if (char1 === ' ' && char2 === 's')
       {//replace plurals, too
           cat = replacement + 's';
       }
       else
       {//do not replace if dashes are matched
           cat = char1 === '-' || char2 === '-' ? cat : replacement;
       }
       return char1 + cat + char2;//return replacement string
    });
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar

#7


45  

Match against a global regular expression:

匹配一个全局正则表达式:

anotherString = someString.replace(/cat/g, 'dog');

#8


34  

str = str.replace(/abc/g, '');

Or try the replaceAll function from here:

或者试试这里的replaceAll函数:

What are useful JavaScript methods that extends built-in objects?

扩展内置对象的有用JavaScript方法是什么?

str = str.replaceAll('abc', ''); OR

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: Clarification about replaceAll availability

编辑:澄清重置所有可用性

The 'replaceAll' method is added to String's prototype. This means it will be available for all string objects/literals.

将“replaceAll”方法添加到String的原型中。这意味着它将适用于所有字符串对象/文本。

E.g.

如。

var output = "test this".replaceAll('this', 'that');  //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'

#9


29  

Say you want to replace all the 'abc' with 'x':

比如你想把所有的abc换成x:

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

I was trying to think about something more simple than modifying the string prototype.

我想考虑一些比修改字符串原型更简单的东西。

#10


27  

Use a regular expression:

使用一个正则表达式:

str.replace(/abc/g, '');

#11


25  

Replacing single quotes:

替换单引号:

function JavaScriptEncode(text){
    text = text.replace(/'/g,''')
    // More encode here if required

    return text;
}

#12


21  

//loop it until number occurrences comes to 0. OR simply copy/paste

//循环,直到出现数为0。或者简单的复制/粘贴

    function replaceAll(find, replace, str) 
    {
      while( str.indexOf(find) > -1)
      {
        str = str.replace(find, replace);
      }
      return str;
    }

#13


20  

This is the fastest version that doesn't use regular expressions.

这是最快的不使用正则表达式的版本。

Revised jsperf

修订jsperf

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)
}

It is almost twice as fast as the split and join method.

它几乎是split and join方法的两倍快。

As pointed out in a comment here, this will not work if your omit variable contains place, as in: replaceAll("string", "s", "ss"), because it will always be able to replace another occurrence of the word.

正如在这里的注释中所指出的,如果您的省略变量包含位置(如:replaceAll)(“string”、“s”、“ss”),因为它将始终能够替换单词的另一个出现,那么这将不会起作用。

There is another jsperf with variants on my recursive replace that go even faster (http://jsperf.com/replace-all-vs-split-join/12)!

在我的递归替换中还有另一个带有变体的jsperf,其速度甚至更快(http://jsperf.com/replace-all- vs-spli- join/12)!

  • Update July 27th 2017: It looks like RegExp now has the fastest performance in the recently released Chrome 59.
  • 2017年7月27日更新:看起来RegExp在最近发布的Chrome 59中拥有最快的性能。

#14


15  

function replaceAll(str, find, replace) {
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace); 
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + replaceAll(st2, find, replace);
    }       
  }
  return str;
}

#15


15  

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

worked better for me than the above answers. so new RegExp("abc", 'g') creates a RegExp what matches all occurence ('g' flag) of the text ("abc"). The second part is what gets replaced to, in your case empty string (""). str is the string, and we have to override it, as replace(...) just returns result, but not overrides. In some cases you might want to use that.

对我来说比上面的答案更好。因此,新的RegExp(“abc”、“g”)创建一个RegExp,该RegExp将匹配文本(“abc”)中出现的所有内容(“g”标志)。第二部分是替换为空字符串("")。str是字符串,我们必须重写它,因为replace(…)只返回结果,而不是重写。在某些情况下,您可能想要使用它。

#16


12  

var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/

http://jsfiddle.net/ANHR9/

#17


10  

while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}

#18


9  

If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:

如果您想要查找的内容已经在字符串中,而且手边没有regex逃避程序,那么可以使用join/split:

function replaceMulti(haystack, needle, replacement)
{
    return haystack.split(needle).join(replacement);
}

someString = 'the cat looks like a cat';
anotherString = replaceMulti(someString, 'cat', 'dog');

#19


9  

I like this method (it looks a little cleaner):

我喜欢这个方法(看起来干净一点):

text = text.replace(new RegExp("cat","g"), "dog"); 

#20


9  

If the string contain similar pattern like abccc, you can use this:

如果字符串包含类似abccc这样的模式,您可以使用以下方法:

str.replace(/abc(\s|$)/g, "")

#21


8  

If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.

如果您试图确保正在查找的字符串即使在替换之后也不存在,则需要使用循环。

For example:

例如:

var str = 'test aabcbc';
str = str.replace(/abc/g, '');

When complete, you will still have 'test abc'!

当完成时,你仍然会有“测试abc”!

The simplest loop to solve this would be:

最简单的循环是:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:

但是每次循环替换两次。也许(有被投票否决的风险)可以合并为一种更有效但可读性较差的形式:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]

这在查找重复字符串时特别有用。例如,如果我们有a, b,我们希望删除所有重复的逗号。[在这种情况下,可以使用.replace(/,+/g,','),但在某些时候,regex会变得非常复杂和缓慢,足以进行循环。]

#22


7  

You can simply use below method

你可以简单地使用下面的方法

/**
 * Replace all the occerencess of $find by $replace in $originalString
 * @param  {originalString} input - Raw string.
 * @param  {find} input - Target key word or regex that need to be replaced.
 * @param  {replace} input - Replacement key word
 * @return {String}       Output string
 */
function replaceAll(originalString, find, replace) {
  return originalString.replace(new RegExp(find, 'g'), replace);
};

#23


7  

Although people have mentioned the use of regex but there's a better approach if you want to replace the text irrespective of the case of the text. Like uppercase or lowercase. Use below syntax

虽然人们已经提到了regex的使用,但是如果您想替换文本,而不考虑文本的情况,还有更好的方法。像大写或小写。使用下面的语法

//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');

//Output will be all the occurrences removed irrespective of casing.

You can refer the detailed example here.

您可以参考这里的详细示例。

#24


7  

var string  = 'Test abc Test abc Test abc Test abc'
string = string.replace(/abc/g, '')
console.log(string)

#25


6  

You could try combining this two powerful methods.

您可以尝试将这两种强大的方法结合起来。

"test abc test test abc".split("abc").join("")

Hope it helps!

希望它可以帮助!

#26


6  

Just add /g

只需添加/ g

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

to

// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

/g means global

/ g意味着全球

#27


6  

Following function works for me:

以下功能适合我:

String.prototype.replaceAllOccurence = function(str1, str2, ignore) 
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;

now call the functions like this:

现在像这样调用函数:

"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");

Simply copy and paste this code in your browser console to TEST.

只需将此代码复制并粘贴到浏览器控制台进行测试。

#28


5  

I use p to store the result from the previous recursion replacement:

我使用p存储之前递归替换的结果:

function replaceAll(s, m, r, p) {
    return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}

It will replace all occurrences in the string s until it is possible:

它将替换字符串s中的所有事件,直到有可能:

replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'

To avoid infinite loop I check if the replacement r contains a match m:

为了避免无限循环,我检查替换后的r是否包含匹配的m:

replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'

#29


4  

My implementation, very self explanatory

我的实现,非常不言自明

function replaceAll(string, token, newtoken) {
    if(token!=newtoken)
    while(string.indexOf(token) > -1) {
        string = string.replace(token, newtoken);
    }
    return string;
}

#30


4  

Most people are likely doing this to encode a URL. To encode a URL, you shouldn't only consider spaces, but convert the entire string properly with encodeURI.

大多数人可能这样做是为了对URL进行编码。要对URL进行编码,不仅要考虑空格,还要使用encodeURI正确地转换整个字符串。

encodeURI("http://www.google.com/a file with spaces.html")

to get:

得到:

http://www.google.com/a%20file%20with%20spaces.html

#1


1558  

For the sake of completeness, I got to thinking about which method I should use to do this. There are basically two ways to do this as suggested by the other answers on this page.

为了完整性起见,我考虑了应该使用哪种方法来实现这一点。在这一页上,有两种方法可以解决这个问题。

Note: In general, extending the built-in prototypes in JavaScript is generally not recommended. I am providing as extensions on the String prototype simply for purposes of illustration, showing different implementations of a hypothetical standard method on the String built-in prototype.

注意:通常不推荐在JavaScript中扩展内置原型。我在String原型上提供的扩展只是为了说明,在String内置原型上显示了一个假想的标准方法的不同实现。


Regular Expression Based Implementation

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

Split and Join (Functional) Implementation

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

Not knowing too much about how regular expressions work behind the scenes in terms of efficiency, I tended to lean toward the split and join implementation in the past without thinking about performance. When I did wonder which was more efficient, and by what margin, I used it as an excuse to find out.

由于不太了解正则表达式在幕后如何高效地工作,我过去倾向于使用分割和加入实现,而不考虑性能。当我真的想知道哪一种更有效,用什么优势,我就以此为借口找出答案。

On my Chrome Windows 8 machine, the regular expression based implementation is the fastest, with the split and join implementation being 53% slower. Meaning the regular expressions are twice as fast for the lorem ipsum input I used.

在我的Chrome Windows 8机器上,基于正则表达式的实现速度最快,分割和连接实现速度慢53%。这意味着我使用的lorem ipsum输入的正则表达式速度是原来的两倍。

Check out this benchmark running these two implementations against each other.

检查一下运行这两个实现的基准。


As noted in the comment below by @ThomasLeduc and others, there could be an issue with the regular expression-based implementation if search contains certain characters which are reserved as special characters in regular expressions. The implementation assumes that the caller will escape the string beforehand or will only pass strings that are without the characters in the table in Regular Expressions (MDN).

正如@ThomasLeduc和其他人在下面的评论中所指出的,如果搜索包含正则表达式中作为特殊字符保留的某些字符,那么基于正则表达式的实现可能会有问题。实现假定调用者将事先转义字符串,或者只传递正则表达式(MDN)中表中没有字符的字符串。

MDN also provides an implementation to escape our strings. It would be nice if this was also standardized as RegExp.escape(str), but alas, it does not exist:

MDN还提供了一个实现来转义我们的字符串。如果它也被标准化为regexpe .escape(str),那就太好了,但可惜它并不存在:

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

We could call escapeRegExp within our String.prototype.replaceAll implementation, however, I'm not sure how much this will affect the performance (potentially even for strings for which the escape is not needed, like all alphanumeric strings).

我们可以在string。prototype中调用escapeRegExp。然而,replaceAll实现并不确定这会对性能产生多大影响(甚至可能对不需要转义的字符串,比如所有的字母数字字符串)。

#2


3529  

str = str.replace(/abc/g, '');

In response to comment:

在回应评论:

var find = 'abc';
var re = new RegExp(find, 'g');

str = str.replace(re, '');

In response to Click Upvote's comment, you could simplify it even more:

作为对Upvote评论的回应,您可以进一步简化它:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

Note: Regular expressions contain special (meta) characters, and as such it is dangerous to blindly pass an argument in the find function above without pre-processing it to escape those characters. This is covered in the Mozilla Developer Network's JavaScript Guide on Regular Expressions, where they present the following utility function:

注意:正则表达式包含特殊的(元)字符,因此,在上面的find函数中盲目地传递一个参数而不进行预处理以转义这些字符是危险的。这在Mozilla开发人员网络关于正则表达式的JavaScript指南中有所介绍,其中介绍了以下实用功能:

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

So in order to make the replaceAll() function above safer, it could be modified to the following if you also include escapeRegExp:

因此,为了使上面的replaceAll()函数更安全,如果还包括escapeRegExp,可以将其修改为如下:

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

#3


1185  

Note: Don't use this in real code.

注意:不要在真正的代码中使用它。

As an alternative to regular expressions for a simple literal string, you could use

作为对简单文字字符串的正则表达式的替代,您可以使用

str = "Test abc test test abc test...".split("abc").join("");

The general pattern is

一般的模式是

str.split(search).join(replacement)

This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers. So, this should really only be used as a quick hack to avoid needing to escape the regular expression, not in real code.

在某些情况下,这比使用replaceAll和正则表达式要快,但在现代浏览器中似乎不再如此。因此,这应该只是作为一种快速的技巧来使用,以避免需要转义正则表达式,而不是在真正的代码中。

#4


493  

Using a regular expression with the g flag set will replace all:

使用带有g标志集的正则表达式将替换所有:

someString = 'the cat looks like a cat';
anotherString = someString.replace(/cat/g, 'dog');
// anotherString now contains "the dog looks like a dog"

See here also

#5


90  

Here's a string prototype function based on the accepted answer:

下面是一个基于公认答案的字符串原型函数:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find, 'g'), replace);
};

EDIT

编辑

If your find will contain special characters then you need to escape them:

如果你的发现将包含特殊字符,那么你需要转义它们:

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};

Fiddle: http://jsfiddle.net/cdbzL/

小提琴:http://jsfiddle.net/cdbzL/

#6


75  

Update:

更新:

It's somewhat late for an update, but since I just stumbled on this question, and noticed that my previous answer is not one I'm happy with. Since the question involved replaceing a single word, it's incredible nobody thought of using word boundaries (\b)

更新有点晚了,但是因为我刚刚遇到这个问题,并且注意到我之前的答案不是我喜欢的。因为这个问题涉及替换一个单词,所以没有人想到使用单词边界(只\b)

'a cat is not a caterpillar'.replace(/\bcat\b/gi,'dog');
//"a dog is not a caterpillar"

This is a simple regex that avoids replacing parts of words in most cases. However, a dash - is still considered a word boundary. So conditionals can be used in this case to avoid replacing strings like cool-cat:

这是一个简单的正则表达式,避免在大多数情况下替换部分单词。然而,破折号仍然被认为是一个词的边界。所以在这种情况下,条件句可以用来避免替换像cool-cat这样的字符串:

'a cat is not a cool-cat'.replace(/\bcat\b/gi,'dog');//wrong
//"a dog is not a cool-dog" -- nips
'a cat is not a cool-cat'.replace(/(?:\b([^-]))cat(?:\b([^-]))/gi,'$1dog$2');
//"a dog is not a cool-cat"

basically, this question is the same as the question here: Javascript replace " ' " with " '' "

基本上,这个问题和这里的问题是一样的:用Javascript代替" ' "

@Mike, check the answer I gave there... regexp isn't the only way to replace multiple occurrences of a subsrting, far from it. Think flexible, think split!

@Mike,看看我给出的答案……regexp并不是唯一的方法来替换多次出现的subsrting,远非如此。灵活,认为分裂!

var newText = "the cat looks like a cat".split('cat').join('dog');

Alternatively, to prevent replacing word parts -which the approved answer will do, too! You can get around this issue using regular expressions that are, I admit, somewhat more complex and as an upshot of that, a tad slower, too:

另外,为了防止替换单词部件——批准的答案也可以!您可以使用正则表达式来解决这个问题,我承认,这些表达式有些复杂,因此也会稍微慢一点:

var regText = "the cat looks like a cat".replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");

The output is the same as the accepted answer, however, using the /cat/g expression on this string:

但是,使用该字符串上的/cat/g表达式,输出与已接受的答案相同:

var oops = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/cat/g,'dog');
//returns "the dog looks like a dog, not a dogerpillar or cooldog" ?? 

Oops indeed, this probably isn't what you want. What is, then? IMHO, a regex that only replaces 'cat' conditionally. (ie not part of a word), like so:

糟糕,这可能不是你想要的。那么,是什么呢?IMHO是一个正则表达式,只在条件下替换“cat”。像这样:

var caterpillar = 'the cat looks like a cat, not a caterpillar or coolcat'.replace(/(?:(^|[^a-z]))(([^a-z]*)(?=cat)cat)(?![a-z])/gi,"$1dog");
//return "the dog looks like a dog, not a caterpillar or coolcat"

My guess is, this meets your needs. It's not fullproof, of course, but it should be enough to get you started. I'd recommend reading some more on these pages. This'll prove useful in perfecting this expression to meet your specific needs.

我的猜测是,这符合你的需要。当然,这并不是充分的证明,但它应该足以让你开始。我建议多读一些这几页。这将证明在完善这个表达式以满足您的特定需求时是有用的。

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.javascriptkit.com/jsref/regexp.shtml

http://www.regular-expressions.info

http://www.regular-expressions.info


Final addition:

最后补充:

Given that this question still gets a lot of views, I thought I might add an example of .replace used with a callback function. In this case, it dramatically simplifies the expression and provides even more flexibility, like replacing with correct capitalisation or replacing both cat and cats in one go:

考虑到这个问题仍然有很多视图,我想我可以添加一个.replace示例,使用回调函数。在这种情况下,它极大地简化了表达式,并提供了更大的灵活性,比如用正确的大小写替换,或者一次替换猫和猫:

'Two cats are not 1 Cat! They\'re just cool-cats, you caterpillar'
   .replace(/(^|.\b)(cat)(s?\b.|$)/gi,function(all,char1,cat,char2)
    {
       //check 1st, capitalize if required
       var replacement = (cat.charAt(0) === 'C' ? 'D' : 'd') + 'og';
       if (char1 === ' ' && char2 === 's')
       {//replace plurals, too
           cat = replacement + 's';
       }
       else
       {//do not replace if dashes are matched
           cat = char1 === '-' || char2 === '-' ? cat : replacement;
       }
       return char1 + cat + char2;//return replacement string
    });
//returns:
//Two dogs are not 1 Dog! They're just cool-cats, you caterpillar

#7


45  

Match against a global regular expression:

匹配一个全局正则表达式:

anotherString = someString.replace(/cat/g, 'dog');

#8


34  

str = str.replace(/abc/g, '');

Or try the replaceAll function from here:

或者试试这里的replaceAll函数:

What are useful JavaScript methods that extends built-in objects?

扩展内置对象的有用JavaScript方法是什么?

str = str.replaceAll('abc', ''); OR

var search = 'abc';
str = str.replaceAll(search, '');

EDIT: Clarification about replaceAll availability

编辑:澄清重置所有可用性

The 'replaceAll' method is added to String's prototype. This means it will be available for all string objects/literals.

将“replaceAll”方法添加到String的原型中。这意味着它将适用于所有字符串对象/文本。

E.g.

如。

var output = "test this".replaceAll('this', 'that');  //output is 'test that'.
output = output.replaceAll('that', 'this'); //output is 'test this'

#9


29  

Say you want to replace all the 'abc' with 'x':

比如你想把所有的abc换成x:

let some_str = 'abc def def lom abc abc def'.split('abc').join('x')
console.log(some_str) //x def def lom x x def

I was trying to think about something more simple than modifying the string prototype.

我想考虑一些比修改字符串原型更简单的东西。

#10


27  

Use a regular expression:

使用一个正则表达式:

str.replace(/abc/g, '');

#11


25  

Replacing single quotes:

替换单引号:

function JavaScriptEncode(text){
    text = text.replace(/'/g,'&apos;')
    // More encode here if required

    return text;
}

#12


21  

//loop it until number occurrences comes to 0. OR simply copy/paste

//循环,直到出现数为0。或者简单的复制/粘贴

    function replaceAll(find, replace, str) 
    {
      while( str.indexOf(find) > -1)
      {
        str = str.replace(find, replace);
      }
      return str;
    }

#13


20  

This is the fastest version that doesn't use regular expressions.

这是最快的不使用正则表达式的版本。

Revised jsperf

修订jsperf

replaceAll = function(string, omit, place, prevstring) {
  if (prevstring && string === prevstring)
    return string;
  prevstring = string.replace(omit, place);
  return replaceAll(prevstring, omit, place, string)
}

It is almost twice as fast as the split and join method.

它几乎是split and join方法的两倍快。

As pointed out in a comment here, this will not work if your omit variable contains place, as in: replaceAll("string", "s", "ss"), because it will always be able to replace another occurrence of the word.

正如在这里的注释中所指出的,如果您的省略变量包含位置(如:replaceAll)(“string”、“s”、“ss”),因为它将始终能够替换单词的另一个出现,那么这将不会起作用。

There is another jsperf with variants on my recursive replace that go even faster (http://jsperf.com/replace-all-vs-split-join/12)!

在我的递归替换中还有另一个带有变体的jsperf,其速度甚至更快(http://jsperf.com/replace-all- vs-spli- join/12)!

  • Update July 27th 2017: It looks like RegExp now has the fastest performance in the recently released Chrome 59.
  • 2017年7月27日更新:看起来RegExp在最近发布的Chrome 59中拥有最快的性能。

#14


15  

function replaceAll(str, find, replace) {
  var i = str.indexOf(find);
  if (i > -1){
    str = str.replace(find, replace); 
    i = i + replace.length;
    var st2 = str.substring(i);
    if(st2.indexOf(find) > -1){
      str = str.substring(0,i) + replaceAll(st2, find, replace);
    }       
  }
  return str;
}

#15


15  

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

worked better for me than the above answers. so new RegExp("abc", 'g') creates a RegExp what matches all occurence ('g' flag) of the text ("abc"). The second part is what gets replaced to, in your case empty string (""). str is the string, and we have to override it, as replace(...) just returns result, but not overrides. In some cases you might want to use that.

对我来说比上面的答案更好。因此,新的RegExp(“abc”、“g”)创建一个RegExp,该RegExp将匹配文本(“abc”)中出现的所有内容(“g”标志)。第二部分是替换为空字符串("")。str是字符串,我们必须重写它,因为replace(…)只返回结果,而不是重写。在某些情况下,您可能想要使用它。

#16


12  

var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

http://jsfiddle.net/ANHR9/

http://jsfiddle.net/ANHR9/

#17


10  

while (str.indexOf('abc') !== -1)
{
    str = str.replace('abc', '');
}

#18


9  

If what you want to find is already in a string, and you don't have a regex escaper handy, you can use join/split:

如果您想要查找的内容已经在字符串中,而且手边没有regex逃避程序,那么可以使用join/split:

function replaceMulti(haystack, needle, replacement)
{
    return haystack.split(needle).join(replacement);
}

someString = 'the cat looks like a cat';
anotherString = replaceMulti(someString, 'cat', 'dog');

#19


9  

I like this method (it looks a little cleaner):

我喜欢这个方法(看起来干净一点):

text = text.replace(new RegExp("cat","g"), "dog"); 

#20


9  

If the string contain similar pattern like abccc, you can use this:

如果字符串包含类似abccc这样的模式,您可以使用以下方法:

str.replace(/abc(\s|$)/g, "")

#21


8  

If you are trying to ensure that the string you are looking for won't exist even after the replacement, you need to use a loop.

如果您试图确保正在查找的字符串即使在替换之后也不存在,则需要使用循环。

For example:

例如:

var str = 'test aabcbc';
str = str.replace(/abc/g, '');

When complete, you will still have 'test abc'!

当完成时,你仍然会有“测试abc”!

The simplest loop to solve this would be:

最简单的循环是:

var str = 'test aabcbc';
while (str != str.replace(/abc/g, '')){
   str.replace(/abc/g, '');
}

But that runs the replacement twice for each cycle. Perhaps (at risk of being voted down) that can be combined for a slightly more efficient but less readable form:

但是每次循环替换两次。也许(有被投票否决的风险)可以合并为一种更有效但可读性较差的形式:

var str = 'test aabcbc';
while (str != (str = str.replace(/abc/g, ''))){}
// alert(str); alerts 'test '!

This can be particularly useful when looking for duplicate strings.
For example, if we have 'a,,,b' and we wish to remove all duplicate commas.
[In that case, one could do .replace(/,+/g,','), but at some point the regex gets complex and slow enough to loop instead.]

这在查找重复字符串时特别有用。例如,如果我们有a, b,我们希望删除所有重复的逗号。[在这种情况下,可以使用.replace(/,+/g,','),但在某些时候,regex会变得非常复杂和缓慢,足以进行循环。]

#22


7  

You can simply use below method

你可以简单地使用下面的方法

/**
 * Replace all the occerencess of $find by $replace in $originalString
 * @param  {originalString} input - Raw string.
 * @param  {find} input - Target key word or regex that need to be replaced.
 * @param  {replace} input - Replacement key word
 * @return {String}       Output string
 */
function replaceAll(originalString, find, replace) {
  return originalString.replace(new RegExp(find, 'g'), replace);
};

#23


7  

Although people have mentioned the use of regex but there's a better approach if you want to replace the text irrespective of the case of the text. Like uppercase or lowercase. Use below syntax

虽然人们已经提到了regex的使用,但是如果您想替换文本,而不考虑文本的情况,还有更好的方法。像大写或小写。使用下面的语法

//Consider below example
originalString.replace(/stringToBeReplaced/gi, '');

//Output will be all the occurrences removed irrespective of casing.

You can refer the detailed example here.

您可以参考这里的详细示例。

#24


7  

var string  = 'Test abc Test abc Test abc Test abc'
string = string.replace(/abc/g, '')
console.log(string)

#25


6  

You could try combining this two powerful methods.

您可以尝试将这两种强大的方法结合起来。

"test abc test test abc".split("abc").join("")

Hope it helps!

希望它可以帮助!

#26


6  

Just add /g

只需添加/ g

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

to

// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

/g means global

/ g意味着全球

#27


6  

Following function works for me:

以下功能适合我:

String.prototype.replaceAllOccurence = function(str1, str2, ignore) 
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;

now call the functions like this:

现在像这样调用函数:

"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");

Simply copy and paste this code in your browser console to TEST.

只需将此代码复制并粘贴到浏览器控制台进行测试。

#28


5  

I use p to store the result from the previous recursion replacement:

我使用p存储之前递归替换的结果:

function replaceAll(s, m, r, p) {
    return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}

It will replace all occurrences in the string s until it is possible:

它将替换字符串s中的所有事件,直到有可能:

replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'

To avoid infinite loop I check if the replacement r contains a match m:

为了避免无限循环,我检查替换后的r是否包含匹配的m:

replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'

#29


4  

My implementation, very self explanatory

我的实现,非常不言自明

function replaceAll(string, token, newtoken) {
    if(token!=newtoken)
    while(string.indexOf(token) > -1) {
        string = string.replace(token, newtoken);
    }
    return string;
}

#30


4  

Most people are likely doing this to encode a URL. To encode a URL, you shouldn't only consider spaces, but convert the entire string properly with encodeURI.

大多数人可能这样做是为了对URL进行编码。要对URL进行编码,不仅要考虑空格,还要使用encodeURI正确地转换整个字符串。

encodeURI("http://www.google.com/a file with spaces.html")

to get:

得到:

http://www.google.com/a%20file%20with%20spaces.html