\"foo bar\"" />
开发者

javascript delete all occurrences of a char in a string

I want to delete all characters lik开发者_开发技巧e [ 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('&','');


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.


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&
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜