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 g
lobal 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&
精彩评论