Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript delete all occurrences of a char in a string

I want to delete all characters like [ or ] or & in a string i.E. : "[foo] & bar" -> "foo bar"

I don't want to call replace 3 times, is there an easier way than just coding:

var s="[foo] & bar";

s=s.replace('[','');

s=s.replace(']','');

s=s.replace('&','');

like image 374
Sonnenhut Avatar asked Aug 06 '11 13:08

Sonnenhut


People also ask

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

Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.

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.

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.


1 Answers

Regular expressions [xkcd] (I feel like him ;)):

s = s.replace(/[\[\]&]+/g, ''); 

Reference:

  • MDN - string.replace
  • MDN - Regular Expressions
  • http://www.regular-expressions.info/

Side note:

JavaScript's replace function only replaces the first occurrence of a character. So even your code would not have replaced all the characters, only the first one of each. If you want to replace all occurrences, you have to use a regular expression with the global modifier.

like image 190
Felix Kling Avatar answered Sep 26 '22 01:09

Felix Kling