How do you remove all instances of a character from a string in javascript?

I just coded a benchmark and tested the first 3 answers. It seems that for short strings (<500 characters)
the third most voted answer is faster than the second most voted one.

For long strings (add ".repeat(300)" to the test string) the faster is answer 1 followed by the second and the third.

Note:

The above is true for browsers using v8 engine (chrome/chromium etc).
With firefox (SpiderMonkey engine) the results are totally different
Check for yourselves!! Firefox with the third solution seems to be
more than 4.5 times faster than Chrome with the first solution... crazy :D

function log(data) {
  document.getElementById("log").textContent += data + "\n";
}

benchmark = (() => {

  time_function = function(ms, f, num) {
    var z;
    var t = new Date().getTime();
    for (z = 0;
      ((new Date().getTime() - t) < ms); z++) f(num);
    return (z / ms)
  } // returns how many times the function was run in "ms" milliseconds.


  function benchmark() {
    function compare(a, b) {
      if (a[1] > b[1]) {
        return -1;
      }
      if (a[1] < b[1]) {
        return 1;
      }
      return 0;
    }

    // functions

    function replace1(s) {
      s.replace(/foo/g, "bar")
    }

String.prototype.replaceAll2 = function(_f, _r){ 

  var o = this.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
//      if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
  {
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;
  }

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;
};

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);
    }

    function replace2(s) {
      s.replaceAll("foo", "bar")
    }

    function replace3(s) {
      s.split('foo').join('bar');
    }

    function replace4(s) {
      s.replaceAll2("foo", "bar")
    }


    funcs = [
      [replace1, 0],
      [replace2, 0],
      [replace3, 0],
      [replace4, 0]
    ];

    funcs.forEach((ff) => {
      console.log("Benchmarking: " + ff[0].name);
      ff[1] = time_function(2500, ff[0], "foOfoobarBaR barbarfoobarf00".repeat(10));
      console.log("Score: " + ff[1]);

    })
    return funcs.sort(compare);
  }

  return benchmark;
})()
log("Starting benchmark...\n");
res = benchmark();
console.log("Winner: " + res[0][0].name + " !!!");
count = 1;
res.forEach((r) => {
  log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")");
});
log("\nWinner code:\n");
log(res[0][0].toString());
<textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>

The test will run for 10s (+2s) as you click the button.

My results (on the same pc):

Chrome/Linux Ubuntu 64:
1. replace1 score: 100% *winner* (766.18)
2. replace4 score: 99.07% speed of winner. (759.11)
3. replace3 score: 68.36% speed of winner. (523.83)
4. replace2 score: 59.35% speed of winner. (454.78)

Firefox/Linux Ubuntu 64
1. replace3 score: 100% *winner* (3480.1)
2. replace1 score: 13.06% speed of winner. (454.83)
3. replace4 score: 9.4% speed of winner. (327.42)
4. replace2 score: 4.81% speed of winner. (167.46)

Nice mess uh?

Took the liberty of adding more test results

Chrome/Windows 10
1. replace1 score: 100% *winner* (742.49)
2. replace4 score: 85.58% speed of winner. (635.44)
3. replace2 score: 54.42% speed of winner. (404.08)
4. replace3 score: 50.06% speed of winner. (371.73)

Firefox/Windows 10
1. replace3 score: 100% *winner* (2645.18)
2. replace1 score: 30.77% speed of winner. (814.18)
3. replace4 score: 22.3% speed of winner. (589.97)
4. replace2 score: 12.51% speed of winner. (331.13)

Edge/Windows 10
1. replace1 score: 100% *winner* (1251.24)
2. replace2 score: 46.63% speed of winner. (583.47)
3. replace3 score: 44.42% speed of winner. (555.92)
4. replace4 score: 20% speed of winner. (250.28)

Chrome on Galaxy Note 4

1. replace4 score: 100% *winner* (99.82)
2. replace1 score: 91.04% speed of winner. (90.88)
3. replace3 score: 70.27% speed of winner. (70.15)
4. replace2 score: 38.25% speed of winner. (38.18)

How do you remove all instances of a character from a string in javascript?

A standard form of string manipulation in JavaScript is to remove the character from the string. So let’s explore all of the ways we can remove the character from a string in JavaScript.

To remove a character from a string in Javascript, there are the following different methods and techniques that you can use,

  1. substr()removes a character from a particular index in the String.
  2. replace()replaces a specific character/string with another character/string.
  3. slice()extracts parts of a string between the given parameters.
  4. Using the string replace() function with a regular expression.

JavaScript String replace()

Javascript String replace() is a built-in method that returns the new String with some matches of the pattern replaced by the replacement. The replace() function replaces the specific character/string with another character/string

The repace() method takes two parameters, the first is the String to be replaced, and the second is the String, which is to be replaced with.

In this case, the first argument is the character to be removed, and the second parameter can be given as the empty string. Then, the replace() method will remove the character from the String. Finally, the replace() method removes the first occurrence of the String.

Syntax

string.replace('characterToReplace', '');

Example

// app.js

str = 'Hello cy Adele';

newStr = str.replace('c', '');

console.log('Original String: ', str);
console.log('After character removed: ', newStr);

Output

node app.js
Original String:  Hello cy Adele
After character removed:  Hello y Adele

In this example, our original String is ‘Hello by Adele’. After using String.replace() and pass the empty character to be replaced for the ‘c‘ character, we successfully removed the ‘c‘ character, and output is ‘Hello y Adele’.

Using a replace() method with a regular expression

To remove a character from a string, use string replace() and regular expression. This combination is used to remove all occurrences of the particular character, unlike the previous function.

A regular expression is used instead of a string along with global property. It will select every occurrence in a string, and it can be removed.

See the following code.

// app.js

str = 'AppDividend';
console.log('Original String: ', str);

newStr = str.replace(/D/g, '');
console.log('After character removed: ', newStr);

Output

node app.js
Original String:  AppDividend
After character removed:  Appividend

You can see that using the regular expression and replace() method, we have replaced D character with nothing, and it has removed the character from the string.

Removing character from string using slice()

JavaScript String slice() function is used to extract parts of a string between the given parameters. The slice() method takes the starting index and the ending index of the string and returns the string in between these indices.

If an ending index is not specified, it is assumed to be the length of the string.

To remove the first character from the string, specify the beginning index to 1. It extracts a string from the second character up to the end of the string.

To remove the last character from the string, specify the ending index to be one less than the length of the string. This extracts a string from the beginning of the string to the second to the last character.

See the following code.

// app.js

str = 'AppDividend';
console.log('Original String: ', str);

removeFirstChar = str.slice(1);
console.log('Removing the first character', removeFirstChar);

removeLastChar = str.slice(0, str.length - 1);
console.log('Removing the last character: ', removeLastChar);

Output

Original String:  AppDividend
Removing the first character ppDividend
Removing the last character:  AppDividen

In this example, we have removed the first and the last character of a string using the slice() method.

To remove the first character, we have passed 1 as an argument.

To remove the last character, we have passed the first argument as 0 and the second as string length – 1.

Removing a specific character using substr()

Javascript string substring() is an inbuilt function that returns a part of the string between the start and end indexes or to the end of a string.

The substr() method can remove a character from the specific index in the string. In addition, the substr() function is used to extract the parts of the string between the given parameters.

The substr() method takes two parameters, the first is the starting index, and the second is the ending index of the string. The function returns the string between these indices is returned.

The portion of the string before and after the character to be removed is separated and joined together. For example, this removes a character from a particular index.

Example

To remove the first character from a string, pass the first parameter as 1 and the second parameter as string.length. It will return the string whose first character is stripped.

// app.js

str = 'AppDividend';
console.log('Original String:', str);

newStr = str.substr(1, str.length);
console.log('After removing the first character:', newStr);

Output

node app.js
Original String: AppDividend
After removing the first character: ppDividend

You can see from the output that the first character is removed.

Conclusion

To remove a character from the start of the string, middle of the string, and at the end of a string, use the str.substr(), str.slice(), and str.replace() methods.

That’s it for this tutorial.

How do you remove all occurrences of a character from a string in JavaScript?

Method 2: Using replace() method with a regular expression: This method is used to remove all occurrences of the specified character, unlike the previous method. A regular expression is used instead of the string along with the global property. It will select every occurrence in the string and it can be removed.

How do you remove all instances of an element from a string?

Remove All Occurrences of a Character From a String in Python Using the translate() Method. We can also use the translate() method to remove characters from a string. The translate() method, when invoked on a string, takes a translation table as an input argument.

How do you remove all occurrences of a substring from a string in JavaScript?

To remove all occurrences of a substring from a string, call the replaceAll() method on the string, passing it the substring as the first parameter and an empty string as the second. The replaceAll method will return a new string, where all occurrences of the substring are removed.

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.