jsRegex學習1
一、js-Regex
是一個描述字元模式的對象。ECMAScript的RegExp類表示Regex。Regex主要用來驗證用戶端的輸入資料、使用者填寫完表單單擊按鈕後,表單就會被發送到伺服器。
二、建立Regex
1、使用new運算子建立
var box=new RegExp('Box');//第一個參數是模式字串(兩個反斜線是Regex的字面量標記法)
var box=new RegExp('box','ig');//第二個參數可選模式修飾符(i:忽略大小寫;g:全域匹配;m:多行匹配)
2、使用字面量標記法建立(常用)
var box=/Box/;//使用字面量方式的正則
var boa=/box/ig;//在第二個斜杠後面加上模式修飾符
三、測試Regex
1、使用test()方法
如:
var pattern=new RegExp('Box');//模式
var str='box';//字串
alert(pattern.test(str));//返回的是false,大小寫不一致
var pattern=new RegExp('Box,‘i');//區分大小寫
var str='box';//字串
alert(pattern.test(str));//返回的是true
var pattern=new RegExp('Box,‘i');//區分大小寫
var str='this is a box';//字串
alert(pattern.test(str));//返回的是true,字串中是否包含模式中的正則
2、使用exec()返回匹配數組
var pattern=/Box/i;
var str='tish is a box';
alert(pattern.exec(str));//匹配了返回數組,否則返回null
四、
1、使用match方法擷取匹配數組
var pattern=/box/ig;//全域搜尋
var str="this is a bax!,that is a box too';
alert(str.match(pattern));//匹配到兩個Box;
alert(str.match(pattern).length);//擷取數組的長度
var pattern=/box/i;//沒有開啟全域
var str='this is a bax!,that is a box too';
alert(str.match(pattern));//匹配到第一個字串返回數組;
2.使用search來尋找匹配資料
var patern=/box/ig;
var str='this is a bax!,that is a box too';
alert(str.search(pattern));//尋找到返回第一個匹配位置,否則返回-1;
3、使用replace替換匹配到的資料
var patern=/box/ig;
var str='this is a bax!,that is a box too';
alert(str.search(pattern,'Tom'));//將box替換成了Tom
var patern=/box/i;沒有開啟全域
var str='this is a bax!,that is a box too';
alert(str.search(pattern,'Tom'));//將第一個box替換成了Tom
4、使用split拆分成字串數組
var pattern=//ig;
var str='this is a bax!,that is a box too';
alert(st.split(pattern));//將空格拆開分成數組