JS中正則表達式的運用解析
正則表達式
@jarringslee
//6-16位字母數(shù)字下劃線
/^[a-zA-Z0-9_-]{6,16}$/
// 手機號驗證(11 位)
/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
// 6 位數(shù)字驗證碼
/^\d{6}$/
// 密碼:6–20 位,僅字母、數(shù)字、下劃線或短橫線
/^[a-zA-Z0-9_-]{6,20}$/語法與基本使用
正則表達式(Regular Expression)是一種字符串匹配的模式(規(guī)則)
使用場景:
- 例如驗證表單:手機號表單要求用戶只能輸入11位的數(shù)字 (匹配)
- 過濾掉頁面內容中的一些敏感詞(替換),或從字符串中獲取我們想要的特定部分(提取)等
- 使用正則
exec()方法用來在字符串中執(zhí)行正則搜索并返回第一個匹配結果的信息- 如果匹配成功,返回一個數(shù)組(含下標、分組等);如果失敗,返回
null
<body>
<script>
// 正則表達式的 exec 使用
const str = 'web前端開發(fā)'
// 1. 定義規(guī)則
const reg = /web/
// 2. 使用正則 exec()
console.log(reg.exec(str))
// 結果:["web", index: 0, input: "web前端開發(fā)", groups: undefined]
console.log(reg.exec('java開發(fā)'))
// 結果:null
</script>
</body>exec()方法用來在字符串中執(zhí)行正則搜索并返回第一個匹配結果的信息- 如果匹配成功,返回一個數(shù)組(含下標、分組等);如果失敗,返回
null
<body>
<script>
// 正則表達式的 exec 使用
const str = 'web前端開發(fā)'
// 1. 定義規(guī)則
const reg = /web/
// 2. 使用正則 exec()
console.log(reg.exec(str))
// 結果:["web", index: 0, input: "web前端開發(fā)", groups: undefined]
console.log(reg.exec('java開發(fā)'))
// 結果:null
</script>
</body>用for循環(huán)遍歷檢查數(shù)組:
用 for 循環(huán)或 some 一行就能搞定:
// 待檢查數(shù)組
const arr = ['apple', 'banana', 'cat'];
// 要檢查的子串
const key = 'a';
// 方法1:for 循環(huán)
for (let i = 0; i < arr.length; i++) {
if (arr[i].includes(key)) {
console.log(`第${i}項 "${arr[i]}" 包含 "${key}"`);
}
}
// 方法2:一行 some
const has = arr.some(str => str.includes(key));
console.log('數(shù)組里至少有一項包含:', has);includes()判斷字符串是否包含子串。some()只要有一項滿足就返回true;全部不滿足返回false。
元字符
- 普通字符:
- 大多數(shù)的字符僅能夠描述它們本身,這些字符稱作普通字符,例如所有的字母和數(shù)字。
- 普通字符只能夠匹配字符串中與它們相同的字符。
- 比如,規(guī)定用戶只能輸入英文26個英文字母,普通字符的話 /[abcdefghijklmnopqrstuvwxyz]/
- 元字符(特殊字符)
- 是一些具有特殊含義的字符,可以極大提高了靈活性和強大的匹配功能。
- 比如,規(guī)定用戶只能輸入英文26個英文字母,換成元字符寫法: /[a-z]/
邊界符
正則表達式中的邊界符(位置符)用來提示字符所處的位置,主要有兩個字符
- ^ 表示匹配行首的文本(從誰開始)
- $ 表示匹配行尾的文本(從誰結束)
如果 ^ 和 $ 在一起,表示必須是精確匹配
<body>
<script>
// 元字符之邊界符
// 1. 匹配開頭的位置 ^
const reg = /^web/
console.log(reg.test('web前端')) // true
console.log(reg.test('前端web')) // false
console.log(reg.test('前端web學習')) // false
console.log(reg.test('we')) // false
// 2. 匹配結束的位置 $
const reg1 = /web$/
console.log(reg1.test('web前端')) // false
console.log(reg1.test('前端web')) // true
console.log(reg1.test('前端web學習')) // false
console.log(reg1.test('we')) // false
// 3. 精確匹配 ^ $
const reg2 = /^web$/
console.log(reg2.test('web前端')) // false
console.log(reg2.test('前端web')) // false
console.log(reg2.test('前端web學習')) // false
console.log(reg2.test('we')) // false
console.log(reg2.test('web')) // true
console.log(reg2.test('webweb')) // flase
</script>
</body>量詞
量詞用來設定某個模式重復次數(shù)
注意: 逗號左右兩側千萬不要出現(xiàn)空格
<body>
<script>
// 元字符之量詞
// 1. * 重復次數(shù) >= 0 次
const reg1 = /^w*$/
console.log(reg1.test('')) // true
console.log(reg1.test('w')) // true
console.log(reg1.test('ww')) // true
console.log('-----------------------')
// 2. + 重復次數(shù) >= 1 次
const reg2 = /^w+$/
console.log(reg2.test('')) // false
console.log(reg2.test('w')) // true
console.log(reg2.test('ww')) // true
console.log('-----------------------')
// 3. ? 重復次數(shù) 0 || 1
const reg3 = /^w?$/
console.log(reg3.test('')) // true
console.log(reg3.test('w')) // true
console.log(reg3.test('ww')) // false
console.log('-----------------------')
// 4. {n} 重復 n 次
const reg4 = /^w{3}$/
console.log(reg4.test('')) // false
console.log(reg4.test('w')) // flase
console.log(reg4.test('ww')) // false
console.log(reg4.test('www')) // true
console.log(reg4.test('wwww')) // false
console.log('-----------------------')
// 5. {n,} 重復次數(shù) >= n
const reg5 = /^w{2,}$/
console.log(reg5.test('')) // false
console.log(reg5.test('w')) // false
console.log(reg5.test('ww')) // true
console.log(reg5.test('www')) // true
console.log('-----------------------')
// 6. {n,m} n =< 重復次數(shù) <= m
const reg6 = /^w{2,4}$/
console.log(reg6.test('w')) // false
console.log(reg6.test('ww')) // true
console.log(reg6.test('www')) // true
console.log(reg6.test('wwww')) // true
console.log(reg6.test('wwwww')) // false
// 7. 注意事項: 逗號兩側千萬不要加空格否則會匹配失敗
</script>范圍
表示字符的范圍,定義的規(guī)則限定在某個范圍,比如只能是英文字母,或者數(shù)字等等,用表示范圍
<body>
<script>
// 元字符之范圍 []
// 1. [abc] 匹配包含的單個字符, 多選1
const reg1 = /^[abc]$/
console.log(reg1.test('a')) // true
console.log(reg1.test('b')) // true
console.log(reg1.test('c')) // true
console.log(reg1.test('d')) // false
console.log(reg1.test('ab')) // false
// 2. [a-z] 連字符 單個
const reg2 = /^[a-z]$/
console.log(reg2.test('a')) // true
console.log(reg2.test('p')) // true
console.log(reg2.test('0')) // false
console.log(reg2.test('A')) // false
// 想要包含小寫字母,大寫字母 ,數(shù)字
const reg3 = /^[a-zA-Z0-9]$/
console.log(reg3.test('B')) // true
console.log(reg3.test('b')) // true
console.log(reg3.test(9)) // true
console.log(reg3.test(',')) // flase
// 用戶名可以輸入英文字母,數(shù)字,可以加下劃線,要求 6~16位
const reg4 = /^[a-zA-Z0-9_]{6,16}$/
console.log(reg4.test('abcd1')) // false
console.log(reg4.test('abcd12')) // true
console.log(reg4.test('ABcd12')) // true
console.log(reg4.test('ABcd12_')) // true
// 3. [^a-z] 取反符
const reg5 = /^[^a-z]$/
console.log(reg5.test('a')) // false
console.log(reg5.test('A')) // true
console.log(reg5.test(8)) // true
</script>
</body>字符類
某些常見模式的簡寫方式,區(qū)分字母和數(shù)字
字符類
示例:
//只能出現(xiàn)一個元素且只能出現(xiàn)一次
/[abc]/.test('andy'); // true
/[abc]/.test('baby'); // true
/[abc]/.test('cry'); // true
/[abc]/.test('die'); // false
//任意字符必須出現(xiàn)n次 /[abc]{n}/
/[abc]{2}/.test('andy'); // false
/[abc]{2}/.test('abef'); // true語法:/[abc]/
含義:只要待測字符串包含 a、b、c 中任意一個字符,即返回 true。
連字符類
示例:
/^[a-z]$/.test('c'); // true應用示例:
/^[1-9][0-9]{4,}$/ // 首字符 1-9,后面位字符 0-9,后面至少 4 位數(shù)字(整體至少五位)// 字符類
console.log(/^[A-Z]$/.test('p')); // false
console.log(/^[A-Z]$/.test('P')); // true
console.log(/^[0-9]$/.test(2)); // true
console.log(/^[a-zA-Z0-9]$/.test(2)); // true
console.log(/^[a-zA-Z0-9]$/.test('p')); // true
console.log(/^[a-zA-Z0-9]$/.test('p')); // true語法:[起始-結束]
含義:匹配 起始到結束 之間的任意一個字符。
[a-z] → 26 個小寫字母
[a-zA-Z] → 大小寫字母
[0-9] → 0~9 任一數(shù)字
騰訊 QQ 號(≥10000)
在 [ ] 里面加上 ^ 取反符號
[^a-z] 匹配除了小寫字母以外的字符
注意要寫到中括號中
小點點 .
匹配除了換行符以外的任何單個字符
用戶名驗證案例
需求
用戶名只能由英文字母、數(shù)字、下劃線或短橫線組成,且長度 6~16 位。
實現(xiàn)步驟
- 正則表達式
/^[a-zA-Z0-9_-]{6,16}$/ - 驗證時機
- 表單失去焦點時立即驗證。
- 結果反饋
- 符合規(guī)范 → 給后面的
<span>添加right類 - 不符合規(guī)范 → 給后面的
<span>添加wrong類
- 符合規(guī)范 → 給后面的
<head>
<style>
span {
display: inline-block;
width: 250px;
height: 30px;
vertical-align: middle;
line-height: 30px;
padding-left: 15px;
}
.error {
color: red;
background: url(./images/error1.png) no-repeat left center;
}
.right {
color: green;
background: url(./images/right.png) no-repeat left center;
}
</style>
</head>
<body>
<input type="text">
<span></span>
<script>
const reg = /^[a-zA-Z0-9_-]{6,16}$/
const input = document.querySelector('input')
const span = input.nextElementSibling
input.addEventListener('blur', function () {
//input的下一個元素
if (reg.test(this.value)) {
span.innerHTML = '輸入正確'
span.className = 'right'
} else {
span.innerHTML = '請輸入6~16位的英文 / 數(shù)字 / 下劃線!'
span.className = 'error'
}
})
</script>
</body>- 預定義 指的是某些常見模式的簡寫方式
- 日期格式示例:
^\d{4}-\d{1,2}-\d{1,2}\d匹配任意 0–9 數(shù)字,等價于[0-9]\D匹配任意非數(shù)字字符,等價于[^0-9]\w匹配字母、數(shù)字或下劃線,等價于[A-Za-z0-9_]\W匹配除字母、數(shù)字、下劃線外的任意字符,等價于[^A-Za-z0-9_]\s匹配任意空白符(空格、Tab、換行等),等價于[ \t\r\n\v\f]\S匹配任意非空白符,等價于[^ \t\r\n\v\f]
- 日期格式示例:
- 修飾符
- 示例:
console.log(/a/i.test('a')); // true
console.log(/a/i.test('A')); // true修飾符應用:替換全局
<body>
<script>
console.log(/^java$/.test('java'))
console.log(/^java$/i.test('JAVA'))
console.log(/^java$/i.test('Java'))
const str = 'java是一門編程語言, 學完JAVA工資很高'
// const re = str.replace(/java|JAVA/g, '前端')
const re = str.replace(/java/ig, '前端')
console.log(re) // 前端是一門編程語言, 學完前端工資很高
</script>
</body>過濾敏感詞小實例:
輸入:你很有激情
點擊后變成:你很有**
<body>
<textarea name="" id="" cols="30" rows="10"></textarea>
<button>發(fā)布</button>
<div></div>
<script>
const tx = document.querySelector('textarea')
const btn = document.querySelector('button')
const div = document.querySelector('div')
btn.addEventListener('click', function () {
// console.log(tx.value)
div.innerHTML = tx.value.replace(/激情|基情/g, '**')
tx.value = ''
})
</script>
</body>約束正則執(zhí)行的某些細節(jié)行為
語法:/表達式/修飾符
i(ignore):匹配時不區(qū)分大小寫g(global):查找全部滿足正則表達式的匹配結果
到此這篇關于JS中正則表達式的運用的文章就介紹到這了,更多相關js正則表達式運用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
到此這篇關于JS中正則表達式的運用解析的文章就介紹到這了,更多相關js正則表達式運用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
select每選擇一個option選項減少對應的option實現(xiàn)方法
這篇文章主要為大家介紹了select每選擇一個option選項減少對應的option實現(xiàn)方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12
一步一步的了解webpack4的splitChunk插件(小結)
這篇文章主要介紹了一步一步的了解webpack4的splitChunk插件(小結),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09

