新聞中心
小編給大家分享一下Javascript常用正則表達(dá)式的示例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
創(chuàng)新互聯(lián)公司主營(yíng)滴道網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,重慶APP軟件開發(fā),滴道h5成都小程序開發(fā)搭建,滴道網(wǎng)站營(yíng)銷推廣歡迎滴道等地區(qū)企業(yè)咨詢
模式修飾符的可選參數(shù)
i: 忽略大小寫
g: 全局匹配
m: 多行匹配
/hello/: 兩個(gè)反斜杠是正則表達(dá)式的字面量表示法
兩個(gè)測(cè)試方法
test
const test = new RegExp('hello world', 'ig'); console.log(test.test('hello world')); // true
exec
返回的是數(shù)組,有就返回?cái)?shù)組的值,沒有返回為null
const test = new RegExp('hello world', 'ig'); console.log(test.exec('hello')); // null
四個(gè)正則表達(dá)式方法
match(pattern)
將所有匹配的字符串組合成數(shù)組返回
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拆分?jǐn)?shù)組
const pattern = / /ig; //空格 const str = "This is a Box! The is a box!"; console.log(str.split(pattern)); //以空格進(jìn)行分割,返回的是數(shù)組 // 輸出結(jié)果 // [ 'This', 'is', 'a', 'Box!', 'The', 'is', 'a', 'box!' ]
匹配模式
\w表示a-zA-Z_
錨元字符匹配(^ $) ^強(qiáng)制收匹配 $強(qiáng)制尾匹配,并且只匹配一個(gè)
const pattern=/^[a-z]oogle\d$/; const str="aoogle2"; console.log(pattern.test(str)); // true
注意: ^符號(hào)在[]里面表示 非 在外邊表示強(qiáng)制首匹配,并且只匹配一個(gè) 要想匹配多個(gè)值,使用+
\b表示到達(dá)邊界
|表示匹配或選擇模式
const pattern=/baidu|google|bing/; //匹配或選擇其中某個(gè)字符,不是相等,包含的意思 const str = "baidu a google"; console.log(pattern.test(str)); //返回true
常用正則表達(dá)式
檢查郵政編碼
const pattern = /^[1-9]{1}[0-9]{5}$/; const str = "122534"; //共6位數(shù),第一位不能為0 console.log(pattern.test(str)); // true
壓縮包后綴名
\w等于a-zA-Z0-9_ 使用^限定從首字母匹配 .是特殊符號(hào)需要\n進(jìn)行轉(zhuǎn)義
|選擇符必須使用()進(jìn)行分組
const pattern = /^[\w]+\.(zip|gz|rar)$/; const str="a12_.zip"; //文件名 字母_數(shù)字.zip,gz,rar console.log(pattern.test(str)); // true
刪除多余空格
方法一: 使用replace只匹配一個(gè),所以使用+匹配多個(gè)
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+'|');
方法三: (.+)貪婪模式,改為惰性模式,使用分組模式,只取匹配的內(nèi)容
var pattern=/^\s+(.+?)\s+$/; var str=" google "; var result=str.replace(pattern,'$1'); //使用分組模式 console.log('|'+result+'|'); // |google|
簡(jiǎn)單郵箱驗(yàn)證
var pattern=/^([\w\.\_]+)@([\w\_]+)\.([a-zA-Z]){2,4}$/; var str="[email protected]"; console.log(pattern.test(str)); // true
以上是“Javascript常用正則表達(dá)式的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
本文標(biāo)題:Javascript常用正則表達(dá)式的示例分析
網(wǎng)頁鏈接:http://fisionsoft.com.cn/article/jiigde.html