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
Try this replaceAll: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8
It is very fast, and it will work for ALL these conditions that many others fail on:
Let me know if you can break it, or you have something better, but make sure it can pass these 4 tests.
Use Regex object like this
var regex = new RegExp('"', 'g'); str = str.replace(regex, '\'');
It will replace all occurrence of
"
into'
.Also you can try:
Just thinking about it from a speed issue I believe the case sensitive example provided in the link above would be by far the fastest solution.
newStr would be "This is a test of the emergency broadcast system."
The easiest would be to use a regular expression with
g
flag to replace all instances:This will replace all occurrences of
foo
withbar
in the stringstr
. If you just have a string, you can convert it to a RegExp object like this:newString now is 'Thas as a strang'