Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest method to replace all instances of a character in a string [duplicate]

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?

like image 397
Anriëtte Myburgh Avatar asked Jan 22 '10 10:01

Anriëtte Myburgh


People also ask

How do I replace multiple characters in a string?

Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.

Does string replace replacing all occurrences?

3.1 The difference between replaceAll() and replace()If search argument is a string, replaceAll() replaces all occurrences of search with replaceWith , while replace() only the first occurence. If search argument is a non-global regular expression, then replaceAll() throws a TypeError exception.

Does replace remove all occurrences?

replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


2 Answers

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"); 
like image 152
Gumbo Avatar answered Sep 30 '22 01:09

Gumbo


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.

like image 32
qwerty Avatar answered Sep 30 '22 01:09

qwerty