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('&','');
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.
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.
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.
Regular expressions [xkcd] (I feel like him ;)):
s = s.replace(/[\[\]&]+/g, '');
Reference:
string.replace
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 g
lobal modifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With