字串查詢和替換函式
要在字串中搜尋字串,有幾個函式:
indexOf( searchString ) 和 lastIndexOf( searchString )
indexOf() 將返回字串中第一次出現 searchString 的索引。如果找不到 searchString,則返回 -1。
var string = "Hello, World!";
console.log( string.indexOf("o") ); // 4
console.log( string.indexOf("foo") ); // -1
同樣,如果沒有找到,lastIndexOf() 將返回最後一次出現 searchstring 或 -1 的索引。
var string = "Hello, World!";
console.log( string.lastIndexOf("o") ); // 8
console.log( string.lastIndexOf("foo") ); // -1
includes( searchString, start )
includes() 將返回一個布林值,告訴 searchString 是否存在於字串中,從索引 start 開始(預設為 0)。如果你只需要測試子字串的存在,這比 indexOf() 更好。
var string = "Hello, World!";
console.log( string.includes("Hello") ); // true
console.log( string.includes("foo") ); // false
replace( regexp|substring, replacement|replaceFunction )
replace() 將返回一個字串,其中出現的所有子字串都與 RegExp regexp 或字串 substring 匹配,字串為 replacement 或 replaceFunction 的返回值。
請注意,這不會修改字串,但返回帶有替換的字串。
var string = "Hello, World!";
string = string.replace( "Hello", "Bye" );
console.log( string ); // "Bye, World!"
string = string.replace( /W.{3}d/g, "Universe" );
console.log( string ); // "Bye, Universe!"
replaceFunction 可用於正規表示式物件的條件替換(即,與 regexp 一起使用)。引數按以下順序排列:
| 引數 | 含義 |
|---|---|
match |
匹配整個正規表示式的子字串 |
g1,g2,g3,… |
正規表示式中的匹配組 |
offset |
整個字串中匹配的偏移量 |
string |
整個字串 |
請注意,所有引數都是可選的。
var string = "heLlo, woRlD!";
string = string.replace( /([a-zA-Z])([a-zA-Z]+)/g, function(match, g1, g2) {
return g1.toUpperCase() + g2.toLowerCase();
});
console.log( string ); // "Hello, World!"