模式修飾符的可選參數
兩個測試方法
test
const test = new RegExp('hello world', 'ig');console.log(test.test('hello world')); // true
exec
返回的是數組,有就返回數組的值,沒有返回為null
const test = new RegExp('hello world', 'ig');console.log(test.exec('hello')); // null
四個正則表達式方法
match(pattern)
將所有匹配的字符串組合成數組返回
const pattern=/Box/ig;const str="This is a Box! The is a box!";console.log(str.match(pattern));
search(pattern)
返回字符串中pattern開始位置,忽略全局匹配
const pattern=/Box/i; //const str="This is a Box! The is a box!";console.log(str.search(pattern)); // 10
replace(pattern)
替換匹配到的字符串
const pattern=/Box/ig;const str="This is a Box! The is a box!";console.log(str.replace(pattern,'Tom'));
split(pattern)
返回字符串指定pattern拆分數組
const pattern = / /ig; //空格const str = "This is a Box! The is a box!";console.log(str.split(pattern)); //以空格進行分割,返回的是數組// 輸出結果// [ 'This', 'is', 'a', 'Box!', 'The', 'is', 'a', 'box!' ]
匹配模式
/w表示a-zA-Z_
錨元字符匹配(^ $) ^強制收匹配 $強制尾匹配,并且只匹配一個
const pattern=/^[a-z]oogle/d$/;const str="aoogle2";console.log(pattern.test(str)); // true
注意: ^符號在[]里面表示 非 在外邊表示強制首匹配,并且只匹配一個 要想匹配多個值,使用+
/b表示到達邊界
|表示匹配或選擇模式
const pattern=/baidu|google|bing/; //匹配或選擇其中某個字符,不是相等,包含的意思const str = "baidu a google"; console.log(pattern.test(str)); //返回true
常用正則表達式
檢查郵政編碼
const pattern = /^[1-9]{1}[0-9]{5}$/;const str = "122534"; //共6位數,第一位不能為0console.log(pattern.test(str)); // true
壓縮包后綴名
/w等于a-zA-Z0-9_ 使用^限定從首字母匹配 .是特殊符號需要/n進行轉義
|選擇符必須使用()進行分組
const pattern = /^[/w]+/.(zip|gz|rar)$/; const str="a12_.zip"; //文件名 字母_數字.zip,gz,rarconsole.log(pattern.test(str)); // true
刪除多余空格
方法一: 使用replace只匹配一個,所以使用+匹配多個
var pattern=/^/s+/; var str=" google "; var result=str.replace(pattern,''); pattern=//s+$/; result=result.replace(pattern,'');
方法二: (.+)貪婪模式,使用惰性模式,后面的空格不讓匹配
var pattern=/^/s+(.+?)/s+$/; var str=" google "; var result=pattern.exec(str,'')[1]; console.log('|'+result+'|');
方法三: (.+)貪婪模式,改為惰性模式,使用分組模式,只取匹配的內容
var pattern=/^/s+(.+?)/s+$/; var str=" google "; var result=str.replace(pattern,'$1'); //使用分組模式 console.log('|'+result+'|'); // |google|
簡單郵箱驗證
var pattern=/^([/w/./_]+)@([/w/_]+)/.([a-zA-Z]){2,4}$/;var str="qzfweb@gmail.com";console.log(pattern.test(str)); // true
以上所述是小編給大家介紹的Javascript常用正則表達式應用講解詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答