字元串對象方法 search方法 String.prototype.search(reg) search方法用於檢索字元串中指定的子字元串,或檢索與正則表達式相匹配的子字元串,方法返回第一個匹配結果的index,查找不到則返回 。 tips: 1.search方法不執行全局匹配,它將忽略標誌g,並且 ...
字元串對象方法
search方法
String.prototype.search(reg)
search方法用於檢索字元串中指定的子字元串,或檢索與正則表達式相匹配的子字元串,方法返回第一個匹配結果的index,查找不到則返回-1
。
'a1b2c3d1'.search('1') // 1
'a1b2c3d1'.search('10') // -1
'a1b2c3d1'.search(/1/) // 1
'a1b2c3d1'.search(/1/g) // 1
'a1b2c3d1'.search(/1/g) // 1
'a1b2c3d1'.search(1) // 1
tips:
1.search方法不執行全局匹配,它將忽略標誌g,並且總是從字元串的開始進行檢索,因此,它不會產生類似於test方法的問題
2.不輸入正則表達式則search方法將會自動將其轉為正則表達式
match方法
String.prototype.match(reg)
match方法將檢索字元串,以找到一個或多個與reg匹配的文本,reg是否具有標誌g
對結果影響很大。
非全局調用
如果reg沒有標識g
,那麼match方法就只能在字元串中執行一次匹配,如果沒有找到任何匹配的文本,將返回null
,否則,它將返回一個數組,其中存放了與它找到的匹配文本有關的信息。
返回數組的第一個元素存放的是匹配文本,而其餘的元素存放的是與正則表達式的子表達式匹配的文本。
除了常規的數組元素之外,返回的數組還含有2個對象屬性:
- index:聲明匹配文本的起始字元在字元串的位置
- input:聲明對stringObject的引用
let reg = /\d(\w)\d/
let text = '$1a2b3c4e5e'
// 子表達式是 /\w/,匹配a
let result = text.match(reg) // ["1a2", "a"]
result.index // 1
// 不管lastIndex
result.lastIndex // 0
result.input // '$1a2b3c4e5e'
全局調用
如果regexp具有標誌g
則match方法將執行全局檢索,找到字元串中的所有匹配子字元串。如果沒有找到任何匹配的子串,否則,返回一個數組。
數組元素中存放的是字元串中所有的匹配子串,而且也沒有index屬性或input屬性。
let reg = /\d(\w)\d/g
let text = '$1a2b3c4e5e'
let result = text.match(reg) // ["1a2", "3c4"]
result.index // undefined
result.input // undefined
result.lastIndex // 0
split方法
String.prototype.split(reg)
我們經常使用split方法將字元串分割為字元數組:
'a, b, c, d'.split(',') // ["a", "b", "c", "d"]
在一些複雜的分割情況下我們可以使用正則表達式解決:
'a, b, c, d'.split(/,/) // ["a", "b", "c", "d"]
'a1b2c3d'.split(/\d/) // ["a", "b", "c", "d"]
replace方法
replace方法有三種形態:
1.String.prototype.replace(str, replaceStr)
2.String.prototype.replace(reg, replaceStr)
'a1b1c1'.replace('1', 2) // 'a2b1c1'
'a1b1c1'.replace(/1/g, 2) // 'a2b2c2'
3.String.prototype.replace(reg, function)
function會在每次匹配替換的時候調用,有四個參數
1.匹配字元串
2.正則表達式分組內容,沒有分組則沒有該參數
3.匹配項在字元串中的index
4.原字元串
'a1b2c3d4e5'.replace(/\d/g, (match, index, origin) => {
console.log(index)
return parseInt(match) + 1
})
// 1 3 5 7 9
// 'a2b3c4d5e6'
'a1b2c3d4e5'.replace(/(\d)(\w)(\d)/g, (match, group1, group2, group3, index, origin) => {
console.log(match)
return group1 + group3
})
// '1b2' '3d4'
// ''a12c34e5 => 去除了第二個分組\w匹配到的b和d