js中如何使用正則去匹配字符串呢?不知道的小伙伴來看看小編今天的分享吧!
1、簡介:
js正則對象有兩種聲明方式:new運算符、字面量方式。
2、使用正則去匹配字符串:
test:
通過test我們能直接檢查某個字符串s中是否存在匹配項;
exec:
非全局模式下,無論如何都是匹配的字符串s中的第一個匹配字串。
let reg = /(t)es(t)/; let s = 'testtest';
let arr = reg.exec(s); console.log(arr);
//[ 'test', 't', 't', index: 0, input: 'testtest' ] let arr1 = reg.exec(s);
console.log(arr1);
//[ 'test', 't', 't', index: 0, input: 'testtest' ]
全局模式下則會遍歷整個字符串查找匹配串。
let reg = /(t)es(t)/g; let s = 'testtest';
let arr = reg.exec(s); console.log(arr);
//[ 'test', 't', 't', index: 0, input: 'testtest' ] let arr1 = reg.exec(s);
console.log(arr1);//[ 'test', 't', 't', index: 4, input: 'testtest' ]
注意:上面輸出結果第二第三項為匹配的分組。
舉例:
let reg = /(t)es(t)/g; let s = 'testtest';
let arr = reg.exec('testtest');
console.log(arr);//[ 'test', 't', 't', index: 0, input: 'testtest' ] let arr1 = reg.exec('testtest');
console.log(arr1);//[ 'test', 't', 't', index: 4, input: 'testtest' ]
分別對兩個不同的'testtest'進行匹配會出現和同一個'testtest'字符串匹配結果一樣的現象。上面的demo中,第一個字符串的遍歷顯然是沒有完成的,正則對象reg會將目前匹配的字符串后的下標也就是4保存在正則對象的lastIndex屬性中,下次進行匹配時,就會從相應的lastIndex下標開始對字符串進行正則匹配。
match:
這個方法和exec有些類似:
在非全局模式下,會匹配分組。
let reg = /(t)es(t)/; console.log(s.match(reg));
//[ 'test', 't', 't', index: 0, input: 'testtest' ] console.log(s.match(reg));
//[ 'test', 't', 't', index: 0, input: 'testtest' ]
全局模式下不會匹配分組,會返回匹配的所有字串。
let reg = /(t)es(t)/;
console.log(s.match(reg));
//[ 'test', 't', 't', index: 0, input: 'testtest' ] console.log(s.match(reg));
//[ 'test', 't', 't', index: 0, input: 'testtest' ]
replace(pattern,replacement):
用replacement將匹配pattern的字段替換
var pattern = /test/g;
var s = 'testtest';
console.log(s.replace(pattern, 'task')); //將test替換成了task
注:模式修飾符必須有g,即全局匹配,才能替換所有的匹配項
search(pattern):
返回字符串中pattern開始的位置;
let pattern = /test/g;
let s = 'testtest';
console.log(s.search(pattern)); //查找到返回位置,否則返回-1
注:其無關乎是否全局匹配,只要找到即返回位置,沒有則返回-1
split(pattern):
將字符串以pattern拆分單位,并返回一個數組,該數組以拆分后的各字段組成;
let pattern = / /g;
let s = 't e s t t e s t';
console.log(s.split(pattern)); //將空格拆開分組成數組
以上就是小編今天的分享了,希望可以幫助到大家。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com