javascript delete all occurrences of a char in a string

Viewed 61727

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('&','');

2 Answers

Today, in 2021 you can use the replaceAll function:

let str = "Hello. My name is John."

let newStr = str.replaceAll('.', '')

console.log(newStr) // result -> Hello My name is John

let nextStr = str.replaceAll('.', '&')

console.log(nextStr) // result -> Hello& My name is John&
Related