String.prototype.replace--替換字串
str.replace(regexp|substr, newSubStr|function)
API本身不改變原本的字串,只是返回新的字串
例子:用函式作為第二個引數
function replacer(match, p1, p2, p3, offset, string, namedCaptureGroup) {
console.log('match', match) // abc12345#$*%
console.log('p1, p2, p3', p1, p2, p3) // abc 12345 #$*%
console.log('string', string) // abc12345#$*%
// match 與 string 剛好相同,只是因為match都匹配上了
return [p1, p2, p3].join(' - ')
}
var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString); // abc - 12345 - #$*%
函式的引數分別有:
1. match: 匹配的字串
2. p1,p2,p3...:例如:/(\a+)(\b+)/, p1 ---> \a+; p2 ---> \b+
3. offset: 匹配到的子字串在原字串中的偏移量;(比如:原字串是“abcd”,匹配到的字串是“bc”,那麼這個引數將會是1)
4. 被匹配的原字串
例子:用字串做第二個引數
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
// oranges are round, and oranges are juicy.
console.log(newstr);
例子:用特殊字串做第二引數
"$$": "$"
"$&": 插入匹配的字串
"$`": 插入當前匹配的子串左邊的內容。
"$'": 插入當前匹配的子串右邊的內容。
"$n": $1, $2, $3
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
// Smith, John
console.log(newstr);