String.prototype.replace()
**replace()
**方法返回一個由替換值替換一些或所有匹配的模式后的新字符串。模式可以是一個字符串或者一個正則表達式, 替換值可以是一個字符串或者一個每次匹配都要調用的函數。
//交換兩個單詞
console.log('hu dan'.replace(/(\w+)\s(\w+)/, '$2,$1'));
function addSymbol(match,p1,p2,p3){
return [p1, p2, p3].join('_');
}
let str = 'abc123#$%'.replace(/([^\d]*)(\d*)([^\w]*)/,addSymbol);
console.log(str);//abc_123_#$%
String.prototype.slice()
slice() 方法提取一個字符串的一部分,并返回一新的字符串。
語法
str.slice(beginSlice[, endSlice])
var str1 = 'The morning is upon us.';
var str2 = str1.slice(4, -2);
console.log(str2); // OUTPUT: morning is upon u
String.prototype.substr()
substr() 方法返回一個字符串中從指定位置開始到指定字符數的字符
語法
str.substr(start[, length])
如果 length 為 0 或負值,則 substr 返回一個空字符串。如果忽略 length,則 substr 提取字符,直到字符串末尾。
var str = "abcdefghij";
console.log("(1,2): " + str.substr(1,2)); // (1,2): bc
console.log("(-3,2): " + str.substr(-3,2)); // (-3,2): hi
console.log("(-3): " + str.substr(-3)); // (-3): hij
console.log("(1): " + str.substr(1)); // (1): bcdefghij
console.log("(-20, 2): " + str.substr(-20,2)); // (-20, 2): ab
console.log("(20, 2): " + str.substr(20,2)); // (20, 2):
String.prototype.substring()
substring() 方法返回一個字符串在開始索引到結束索引之間的一個子集, 或從開始索引直到字符串的末尾的一個子集。
語法
str.substring(indexStart[, indexEnd])
如果 indexStart 大于 indexEnd,則 substring 的執行效果就像兩個參數調換了一樣。例如,str.substring(1, 0) == str.substring(0, 1)
var anyString = "Mozilla";
// 輸出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));
// 輸出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));
// 輸出 ""
console.log(anyString.substring(4,4));
// 輸出 "Mozill"
console.log(anyString.substring(0,6));
// 輸出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));
slice 和substring,substr區別
slice和substring接收的是起始位置和結束位置(不包括結束位置),而substr接收的則是起始位置和所要返回的字符串長度。
substring是以兩個參數中較小一個作為起始位置,較大的參數作為結束位置。
當參數中有負數時
- slice將字符串長度與負數相加作為參數;
- substr僅僅是將第一個參數與字符串長度相加后的結果作為第一個參數;
- substring將負數直接當做0.