描述字符串規(guī)則的表達(dá)式
- /pattern/attrs
- new RegExp(pattern,attrs)
regexObj.test(str)
- 測試正則表達(dá)式與指定字符串是否匹配,只要包含就匹配
<input type="text" onblur="check(this)"
onfocus="reset(this)">
<script>
function check (mobileInput) {
var value = mobileInput.value;
if(!/^13566668888$/.test(value)){
mobileInput.style.borderColor="red"
};// body...
}
function reset (mobileInput) {
mobileInput.style.borderColor=""
}
</script>
/13566668888/.test(x13566668888y);//true,只要包含字符串即正確
錨點(diǎn)吟吝,位置匹配
- ^起始位置匹配
/^http:/.test('http://163.com') - $結(jié)尾位置匹配
/.jpg$/ - \b 單詞邊界
/\bis\b/.test('that is nice');//true
/\bis\b/.test('this');//false
/^13566668888$/.test();完全符合才匹配
字符類
匹配一類字符中的一個(gè)
[0-9]:一個(gè)數(shù)字 [^0-9]:非數(shù)字的一個(gè)字符
-[a-z]:一個(gè)字母 [^a-z]. :任一字符,換行除外
/ ^1[0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9]$/元字符
具有特殊意義的字符^颈娜、$剑逃、\b
\d:[0-9] \D:[\d]=[0-9]
\s:空白符 \S:[^\s]
\w:[A-Za-z0-9] \W:[^\w]
量詞
出現(xiàn)的次數(shù)
- {m,n}:m到n次
- :{0,}
- ?:{0,1}
- +:{1官辽,}
/https?/.test('https://www.163.com');//true
/https?/.test('http://www.163.com');//true
量詞對(duì)前一個(gè)字符作用
手機(jī)號(hào)測試
/^1\d{10}$/
轉(zhuǎn)義符
- 需要匹配的字符是元字符蛹磺,需要加轉(zhuǎn)義符
/^http:///
/@163.com$/
多選分支
- 或/(x|y)/=[xy]
特殊的字符類
/.(png|jpg|png|gif)$/
/(.+)@(163|126|188).com$)/任意字符數(shù)@
捕獲
- 保存匹配到的字符串,日后再用
()捕獲
(?:)不捕獲,減少內(nèi)存的占用
使用于:$1,$..., api參數(shù)或返回值 - str.match(regexp)獲取匹配正則式的字符串
var url='https://blog.163.com/album?id=1#comment';
var reg=(/https?:)//([/]+)(/[?])?(?[^#])?(#.)?/;
var arr=url.match(reg);
var protocol=arr[1];
var host=arr[2];
var pathname=arr[3];
var search=arr[4];
var hash=arr[5];
替換
- str.replace(regexp/substr,replacement)
替換一個(gè)子串
var ="the price of potato is 5, the price of apple is 10.";
str.replace(/(\d)+/g,'$1.00);//$1捕獲的字符串存儲(chǔ)的位置,g全局匹配
-
通過函數(shù)同仆,執(zhí)行復(fù)雜的替換
html代碼萤捆,加入實(shí)體字符
<script>
var container = document.getElementById('container');var html = '<label>網(wǎng)址:</label><input placeholder="以http://起始">'; html = html.replace(/[<>]/g, function(m0){ switch(m0){ case '<': return '<'; case '>': return '>'; } }); console.log(html); container.innerHTML = html; </script>
regexpObj.exec(str)強(qiáng)大的檢索
- 更詳盡的結(jié)果
- 過程的狀態(tài)