1.replace
var user='xia&&min**';user=user.replace(/[^A-Za-z/d_-]+/,''); //需要再次賦值console.log(user); //xiamin**user = user.replace(/[^A-Za-z/d_-]+/g, ''); //全局進行替換console.log(user); //xiamin
分割郵件
var email='nettuts@tutsplus.com';var result=email.replace(/([A-Za-z_/d-]+)@([A-Za-z_/d-]+)/.[a-z]{2,4}/ig,'$1,$2');console.log(result); //nettuts tutsplus2.test
這個方法接受單個字符串參數,然后返回一個布爾值,該值表明是否找到一個批評。如果你不需要對特定的匹配結果進行操作,比如,驗證用戶名,“test”方法已足夠完成這個任務。
var name='xiamin';var result=/[A-Za-z-_]+/.test(name);console.log(result);
3.match
與test方法不同,match() 返回一個包含所有找到的批評的數組。
var name='xiamin';var result=name.match(/i/g);console.log(result); //(2) ["i", "i"]
匹配所有問號前后內容
var url ='http://localhost:8080?name=xiamin';var result=url.match(/^(.+)/?(.+)/i);console.log(result);//"http://localhost:8080?name=xiamin?" "http://localhost:8080" "name=xiamin"
匹配#后面的內容
var url ='http://localhost:8080?name=xiamin#dnsjdnw';var result=url.match(/#(.+)/i);console.log(result);//"#dnsjdnw", "dnsjdnw"
獲取協議
var url ='http://localhost:8080?name=xiamin#dnsjdnw';var result=url.match(/(ht|f)tps?:/i);console.log(result);//"http:", "ht"
匹配頁面url
var url ='http://www.baidu.com';var result=url.match(/.+/.[a-z]{2,4}/ig);console.log(result);//http://www.baidu.com以上所述是小編給大家介紹的JavaScript正則表達式簡單實用實例,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對錯新站長站網站的支持!
新聞熱點
疑難解答
圖片精選