replace() 方法用于在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。
str.replace(regexp/substr,replacement)
返回值
一個新的字符串,是用 replacement 替換了 regexp 的第一次匹配或所有匹配之后得到的。
全局替換,每當 "Microsoft" 被找到,它就被替換為 "W3School":
(str.replace(/Microsoft/g, "W3School"))
把 "Doe, John" 轉(zhuǎn)換為 "John Doe" 的形式:
name = "Doe, John";
name.replace(/(\w+)\s, \s(\w+)/, "$2 $1");
把字符串中所有單詞的首字母都轉(zhuǎn)換為大寫
name = 'aaa bbb ccc';
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);
return word.slice(0,1).toUpperCase()+word.slice(1).toLowerCase();