startsWith():字符串是否以指定的內(nèi)容開頭
語法:
布爾值 = str.startsWith(想要查找的內(nèi)容, [position]);
解釋:判斷一個字符串是否以指定的子字符串開頭。如果是,則返回 true;否則返回 false。
參數(shù)中的position:
如果不指定,則默認(rèn)為0。
如果指定,則規(guī)定了檢索的起始位置。檢索的范圍包括:這個指定位置開始,直到字符串的末尾。即:[position, str.length)
舉例:
const name = 'abcdefg';
console.log(name.startsWith('a')); // 打印結(jié)果:true
console.log(name.startsWith('b')); // 打印結(jié)果:false
// 因為指定了起始位置為3,所以是在 defg 這個字符串中檢索。
console.log(name.startsWith('d',3)); // 打印結(jié)果:true
console.log(name.startsWith('c',3)); // 打印結(jié)果:false
endsWith():字符串是否以指定的內(nèi)容結(jié)尾
語法:
布爾值 = str.endsWith(想要查找的內(nèi)容, [position]);
解釋:判斷一個字符串是否以指定的子字符串結(jié)尾。如果是,則返回 true;否則返回 false。
參數(shù)中的position:
如果不指定,則默認(rèn)為 str.length。
如果指定,則規(guī)定了檢索的結(jié)束位置。檢索的范圍包括:從第一個字符串開始,直到這個指定的位置。即:[0, position)
注意此時不能取到position位置的值。或者你可以這樣簡單理解:endsWith() 方法里的position,表示檢索的長度。
注意:startsWith() 和 endsWith()這兩個方法,他們的 position 的含義是不同的,請仔細區(qū)分。
舉例:
const name = 'abcdefg';
console.log(name.endsWith('g')); // 打印結(jié)果:true
console.log(name.endsWith('f')); // 打印結(jié)果:false
// 因為指定了截止位置為3,所以是在 abc 這個長度為3字符串中檢索
console.log(name.endsWith('c', 3)); // 打印結(jié)果:true
console.log(name.endsWith('d', 3)); // 打印結(jié)果:false
replace()
語法:
新的字符串 = str.replace(被替換的字符,新的字符);
解釋:將字符串中的指定內(nèi)容,替換為新的內(nèi)容并返回。不會修改原字符串。
注意:這個方法,默認(rèn)只會替換第一個被匹配到的字符。如果要全局替換,需要使用正則。
代碼舉例:
//replace()方法:替換
var str2 = 'Today is fine day,today is fine day !';
console.log(str2);
console.log(str2.replace('today', 'tomorrow')); //只能替換第一個today
console.log(str2.replace(/today/gi, 'tomorrow')); //這里用到了正則,才能替換所有的today