Fastest method to replace all instances of a chara

2018-12-31 07:06发布

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?

13条回答
若你有天会懂
2楼-- · 2018-12-31 07:46

Try this replaceAll: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8

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

It is very fast, and it will work for ALL these conditions that many others fail on:

"x".replaceAll("x", "xyz");
// xyz

"x".replaceAll("", "xyz");
// xyzxxyz

"aA".replaceAll("a", "b", true);
// bb

"Hello???".replaceAll("?", "!");
// Hello!!!

Let me know if you can break it, or you have something better, but make sure it can pass these 4 tests.

查看更多
零度萤火
3楼-- · 2018-12-31 07:50

Use Regex object like this

var regex = new RegExp('"', 'g'); str = str.replace(regex, '\'');

It will replace all occurrence of " into '.

查看更多
刘海飞了
4楼-- · 2018-12-31 07:52

Also you can try:

string.split('foo').join('bar');
查看更多
裙下三千臣
5楼-- · 2018-12-31 07:52

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.

var token = "\r\n";
var newToken = " ";
var oldStr = "This is a test\r\nof the emergency broadcasting\r\nsystem.";
newStr = oldStr.split(token).join(newToken);

newStr would be "This is a test of the emergency broadcast system."

查看更多
还给你的自由
6楼-- · 2018-12-31 07:53

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
    re = new RegExp(pattern, "g");
查看更多
何处买醉
7楼-- · 2018-12-31 07:53
var mystring = 'This is a string';
var newString = mystring.replace(/i/g, "a");

newString now is 'Thas as a strang'

查看更多
登录 后发表回答