正則表示式使用方法及好用的小工具
阿新 • • 發佈:2020-12-16
技術標籤:正則表示式
正則表示式使用方法及好用的小工具
正則表示式
正則表示式(regular expression)描述了一種字串匹配的模式(pattern),可以用來檢查一個串是否含有某種子串、將匹配的子串替換或者從某個串中取出符合某個條件的子串等。
常用方法
//test()方法 查詢是否有匹配的值 //該方法返回true或者false //注意用法 正則表示式在前 語法: // pattern.test(str) var pattern1 = /world/; var str1 = "hello world ,and the world is beautiful!"; console.log(pattern1.test(str1)); //true //exec()方法 查詢匹配值的資訊 //注意用法 正則表示式在前 語法: // pattern.test(str) var pattern2 = /world/; //該方法有沒有g不影響結果 i有效 var str2 = "hello world ,and the world is beautiful!"; console.log(pattern2.exec(str2)); //返回第一個匹配值的偽陣列 //["world", index: 6, input: "hello world ,and the world is beautiful!", groups: undefined] //match()方法 //與exec()不同在於該方法屬於string的正則表達方法,exec屬於正則表示式方法 //用法也不同 全域性變數g有效 g為全域性 i為不區分大小寫 var pattern3 = /world/gi; var str3 = "hello World ,and the world is beautiful!"; console.log(str3.match(pattern3)); //(2) ["World", "world"] 返回匹配值偽陣列 //search()方法 返回匹配值的索引值 var pattern4 = /world/i; var str4 = "hello World ,and the world is beautiful!"; console.log(str4.search(pattern4)); // 6 //replace()方法 替換匹配值 但不改變原來字串 var pattern5 = /world/i; var str5 = "hello World ,and the world is beautiful!"; console.log(str5.replace(pattern5, "test")); //hello test ,and the world is beautiful! console.log(str5); //hello World ,and the world is beautiful!
好用的工具網址推薦
生成正則表示式:
https://c.runoob.com/front-end/854
檢視正則表示式語義:
https://regexper.com/