标签云

微信群

扫码加入我们

WeChat QR Code

I have this string:"Test abc test test abc test test test abc test test abc"Doingstr = str.replace('abc', '');seems to only remove the first occurrence of abc in the string above. How can I replace all occurrences of it?


stackoverflow.com/questions/1137436/…

2019年05月24日26分29秒

SIMPLEST:var str = 'abcabcbabc'; str.replace(/a/g, 'x'); --> 'xbcxbcxbc

2019年05月24日26分29秒

Beware that Federico's option is great as long as your string-to-be-replaced doesn't include special regex characters.

2019年05月24日26分29秒

Andrew Special regex characters can be escaped to be normal characters.

2019年05月24日26分29秒

For anyone wondering, you can escape a regex by backslash. For example, str.replace(/\]/g) should work, but not str.replace(/]/g) because ']' is a special regex character.

2019年05月23日26分29秒

On Android 4.1 the regexp method is 15% faster, but you are not escaping the expression to search for, so this benchmark is incomplete.

2019年05月24日26分29秒

There is an issue with this solution, if you're search string appears to contains special characters of a regexp expression, they will be interpreted. I recommend the Sandy Unitedwolf answer.

2019年05月24日26分29秒

The first one will do this: 'bla.bla'.replaceAll('.', '_'); "_______". The second one will do 'bla_bla', which is more generally what you want to do.

2019年05月23日26分29秒

Gloss over answer.Go to the next, "incorrect"-marked answer with 5x more votes.That's what you want.

2019年05月24日26分29秒

ThomasLeduc it looks like the issue you mentioned can be worked around with lodash => lodash.com/docs/4.17.5#escapeRegExp

2019年05月23日26分29秒

Regular expressions are the only way to accomplish this "out of the box" without implementing your own 'replaceAll' method.I'm not suggesting their use just for the sake of using them.

2019年05月24日26分29秒

This is my own function from this comment:function replaceAll(find, replace,str) { var re = new RegExp(find, 'g');str = str.replace(re, replace);return str; }

2019年05月24日26分29秒

Major caveat of of the replaceAll implementation is that it won't work if find contains metacharacters.

2019年05月24日26分29秒

SeanBright you're right. I used your javascript in a php code so I had to add an extra backslash to escape. On the fiddle your code is perfect. I should have checked. Apologies jsfiddle.net/7y19xyq8

2019年05月24日26分29秒

Bennett it's bad practice to extend the prototype of JavaScript native types.

2019年05月24日26分29秒

It surprised me, as I would expect this method to be allocating more objects, creating more garbage, and thus take longer, but when I actually tested in a browser this method was consistently about 20% faster than the accepted response. Results may vary, of course.

2019年05月24日26分29秒

I was curious myself, and set up this: jsperf.com/replace-all-vs-split-join . It seems that v8 is just crazy fast at splitting/joining arrays compared to other javascript engines.

2019年05月24日26分29秒

Very nice - also saves you from the possibility of bad RegExps when passing in special characters. I'm adding in a generic flag for "find this and replace it" in an object property, but was concerned if I needed to replace "." or "}" and forgot I was using RegEx 3 months later!

2019年05月24日26分29秒

On my ipad2/safari, split/join is 65% slower than replace so your results may vary.

2019年05月23日26分29秒

And as String.prototype: String.prototype.replaceAll = function(f,r){return this.split(f).join(r);}. Usage: "My string".replaceAll('st', ''); produces "My ring"

2019年05月23日26分29秒

Kinda silly I think, but the JS global regex is the only way to do multiple replaces.

2019年05月24日26分29秒

well technically you can loop through var sourceText count the number of instances (numOfInstances) using substring or split and count the length (among other strategies) of thatWhichYouWantToReplace then do for (var i = 0; i < numOfInstances; i++){ sourceText = sourceText.replace('thatWhichYouWantToReplace', ''); } or even easier just use a while loop (while sourceText.indexOf(thatWhichYouWantToReplace > -1){ sourceText = sourceText.replace(...)) but I don't see why you would want to do it that way when using /g is so easy and probably more performant.

2019年05月23日26分29秒

But what if find contains characters like . or $ that have special meanings in regex?

2019年05月23日26分29秒

callum In that case you'd have to escape your find variable (see edit above).

2019年05月23日26分29秒

Don’t modify objects you don’t own

2019年05月23日26分29秒

jesal, this is a wonderful solution to a string replacement problem I've encountered, and it apparently overcomes the "immutability" of strings in JavaScript. Could you or someone else explain how this prototype function overrides the immutability of strings? This does work; I just want to understand this ancillary question it poses.

2019年05月24日26分29秒

Tom: It doesn't overcome the immutability at all: var str = this creates a second reference to the immutable string, to which the replace method is applied, which in turn returns a new immutable string. these prototype functions return a new immutable string, if not, you'd be able to write someStrVar.replaceAll('o', '0'); and someStrVar would be changed. Instead, you have to write someStrVar = someStrVar.replaceAll('o', '0'); <-- reassign to set the var to hold the new immutable string. there's no way around that. Try in console: x = 'foobar'; x.replaceAll('o', '0'); x;

2019年05月23日26分29秒

I think the additional interesting part should placed at the bottom. ps.: I noticed just now that the half of the first line is out of the area, let me allow to fix that!

2019年05月23日26分29秒

Can you rewrite the replaceAll() function there for those not using prototype?

2019年05月23日26分29秒

Click Upvote....you are using prototype, it's part of all JS objects.I think you are thinking of prototype.js the JS library.

2019年05月24日26分29秒

seth, a little correction. If you add method to a prototype, it is available to all objects of that type. The replceAll method was added to String prototype and it should work for all string objects.

2019年05月23日26分29秒

solutionyogi -- Yep, I've used prototype (correctly) before. I was just addressing the OP's comment about "not using prototype" which I assumed to mean Prototype.js (perhaps incorrectly?).I should have said "a prototype" as I was trying to say JavaScript objects have a prototype. Thus, the OP was already 'using prototype,' albeit in an "indirect" way.Indirect might be the wrong term to use here but I'm tired so mea culpa.

2019年05月24日26分29秒

Simple, easy, and probably the most performant option: nice answer.

2019年05月24日26分29秒

I don't know if it performance-wise, but.... it works.

2019年05月24日26分29秒

Actually, while I haven't metric-ed it personally, split/join is usually a very performant solution.

2019年05月24日26分29秒

it's even in chrome, 100% faster on firefox, and 50% slower on IE...: jsperf.com/replace-regex-split-join

2019年05月23日26分29秒

How can i change second line to replace strings? This doesn't work:text = text.replace('hey', 'hello');Any idea?

2019年05月23日26分29秒

Sure Stefan, here is the code...text = text.replace(/hey/g, 'hello');

2019年05月24日26分29秒

This method is dangerous, do not use it. If the replacement string contains the search keyword, then an infinite loop will occur. At the very least, store the result of .indexOf in a variable, and use this variable as the second parameter of .indexOf (minus length of keyword, plus length of replacement string).

2019年05月24日26分29秒

I'm thinking about first replacing the search pattern with a weired unicode char, of that we are sure it is not used in the input string.Like U+E000 in the private area. And then replace it back to the target. I've build that here.. I'm not sure if thats a good Idea.

1970年01月01日00分03秒

I loved your solution... I wish I could give you +10 but here's my +1. I think you can store index of the sub-string that was replaced and jump to the next if a match is found at a lower index to avoid that infinite loop problem.I can't comment about the performance because I didn't test it but that's just my 2 cents on this piece of excellence.

2019年05月24日26分29秒

fr0zenfyr if you want to check if omit is in place (to prevent infinite loop) you could do a conditional like if(place.replace(omit) === omit) { No match, so it's safe to use replace loop } else { Match so use different method like split and join }

2019年05月24日26分29秒

Hmm.. but whats the point combining two solutions? I'm anyway not a fan of split/join approach anyway.. thanks for the advise..

2019年05月23日26分29秒

Fr0zenFyr I believe the purpose of combining the two solutions would be to fallback on a slower method if you can't use the faster one (when the loop would be infinite for example). So it would be a safe guard to ensure functionality with efficiency, but without possibility of failure.

2019年05月24日26分29秒

Flawed............

2019年05月24日26分29秒

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

2019年05月23日26分29秒

Yeah, you're right. added. also edited it to answer the original question :)

2019年05月23日26分29秒

Note: g flag in regex means it is global flag which will match all occurrences

2019年05月24日26分29秒

I wonder how well that performs ... substring is native or walks over char array to create the new characters.

2019年05月24日26分29秒

Okay, how do you escape the string to use it as a regex pattern?

2019年05月24日26分29秒

I dont, I just use it for plain text

2019年05月24日26分29秒

what was the point of a fiddle that only contains the same javascript

2019年05月24日26分29秒

from the example site: "/toBeReplacedString/gi is the regex you need to use. Here g represents for global match and i represents case insensitive. By default regex is case sensitive"

2019年05月23日26分29秒