国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

淺談Javascript常用正則表達式應用

2024-05-06 15:41:53
字體:
來源:轉載
供稿:網友

模式修飾符的可選參數

i: 忽略大小寫 g: 全局匹配 m: 多行匹配 /hello/: 兩個反斜杠是正則表達式的字面量表示法

兩個測試方法

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,''); 

方法二: (.+)貪婪模式,使用惰性模式,后面的空格不讓匹配

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 台南市| 三亚市| 临颍县| 榆中县| 丰顺县| 福安市| 饶阳县| 沁水县| 常州市| 肥东县| 鹿邑县| 公主岭市| 沅陵县| 泉州市| 平远县| 文山县| 肥城市| 修文县| 巨野县| 安国市| 电白县| 宾川县| 嘉兴市| 托克托县| 汽车| 桦甸市| 佳木斯市| 巴塘县| 宝鸡市| 台北县| 宁强县| 东莞市| 延津县| 泰州市| 沧源| 方山县| 鄄城县| 肥西县| 宣城市| 海宁市| 建阳市|