What is the fastest way to replace all instances of a string/character in a string in JavaScript? A while
, a for
-loop, a regular expression?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- how to split a list into a given number of sub-lis
@Gumbo adding extra answer - user.email.replace(/foo/gi,"bar");
DEMO
You can use the following:
or
This is going to replace all the character that are not letter or numbers to ('_'). Simple change the underscore value for whatever you want to replace it.
I tried a number of these suggestions after realizing that an implementation I had written of this probably close to 10 years ago actually didn't work completely (nasty production bug in an long-forgotten system, isn't that always the way?!)... what I noticed is that the ones I tried (I didn't try them all) had the same problem as mine, that is, they wouldn't replace EVERY occurrence, only the first, at least for my test case of getting "test....txt" down to "test.txt" by replacing ".." with "."... maybe I missed so regex situation? But I digress...
So, I rewrote my implementation as follows. It's pretty darned simple, although I suspect not the fastest but I also don't think the difference will matter with modern JS engines, unless you're doing this inside a tight loop of course, but that's always the case for anything...
Hope that helps someone!
Use the
replace()
method of theString
object.As mentioned in the selected answer, the /g flag should be used in the regex, in order to replace all instances of the substring in the string.
I think the real answer is that it completely depends on what your inputs look like. I created a JsFiddle to try a bunch of these and a couple of my own against various inputs. No matter how I look at the results, I see no clear winner.
This one I wrote seems fastest for small inputs and dense replacements: