定義:
replace()方法用於在字符串中用一些字符替換另一些字符,或者替換一個與正則表達式匹配的子串。返回替換后的字符串,且原字符串不變。
var newStr = str.replace(regexp|substr, newSubStr|function)
regexp/substr: 規定子字符串或者要替換的模式的RegExp對象。如果訪值是字符串,則將它作為要檢索的直接量文本模式,而不是首先被轉換為RegExp對象。
newSubStr/function: 一個字符串值。規定了替換文本或生成替換文本的函數。
1.簡單的字符串替換
let str = 'hello world'; let str1 = str.replace('hello', 'new'); console.log(str1) //new world console.log(str) //hello world
2.正則替換,正則全局匹配需要加上g,否則只會匹配第一個
let str = 'hello world'; let str2 = str.replace(/o/,'zql'); let str3 = str.replace(/o/g,'zql'); console.log(str2) //hellzql world console.log(str3) //hellzql wzqlrld
3.一些常用的特殊的定義
1)$':表示匹配字符串右邊的文本
let str = 'hello world'; let str4 = str.replace(/hello/g, "$'"); let str5 = str.replace(/o/g, "$'"); console.log(str4) // world world console.log(str5) //hell world wrldrld
2) $`(tab鍵上方的字符):表示匹配字符串文本左邊的文本
let str = 'hello world'; let str6 = str.replace(/world/,"$`"); console.log(str6) //hello hello
3)$$: 表示插入一個$
let str = '¥2000.00'; let str7 = str.replace(/¥/,"$$"); console.log(str7) //$2000.00
4. 當第二個參數是函數時
將所有單詞首字母改為大寫
let str = 'please make heath your first proprity';
str1 = str.replace(/\b\w+\b/g, function (word) {
console.log('匹配正則的參數',word);
return word[0].toUpperCase() + word.slice(1);
});
console.log(str1); //Please Make Heath Your First Proprity