jsRegex學習1

來源:互聯網
上載者:User

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));//將空格拆開分成數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.