Sonnenhut
Sonnenhut

Reputation: 4453

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

Upvotes: 41

Views: 81477

Answers (2)

Jo Momma
Jo Momma

Reputation: 1307

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&

Upvotes: 20

Felix Kling
Felix Kling

Reputation: 816334

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

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

Reference:

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.

Upvotes: 79

Related Questions