前端中使用正则表达式,主要在字符串的方法中和正则表达式的方法中。
一.字符串使用正则表达式
1.match(RegExp|String)方法
返回满足表达式的字符串,默认只匹配第一个符合表达式的数据。在正则表达式中定义全局匹配,则返回一个数组。找不到返回null。
let str = "hello, world!"
let res = str.match(/e/)
console.log(res) // e
let resR = str.match(/l/)
console.log(resR ) // l
let resArr = str.match(/l/g)
console.log(resArr) // [l,l,l]
2.replace(RegExp|String, newValue)方法
使用第二个参数替换满足表达式的位置。找不到返回原字符串。
let str = "hello, world!"
let res = str.replace(/l/, "e")
console.log(res); // heelo, world!
let resStr = str.replace(/l/g, "e")
console.log(resStr); // heeeo, wored!
replaceAll(String|RegExp, newValue)有兼容性,并且正则表达式必须设置全局匹配,所以不建议使用。
3.search(RegExp|String)
查询满足正则表达式的字符串,在原字符串的位置,即使有多个满足,也只会返回首个位置。找不到返回-1
let str = "hello, world!"
let res = str.search(/l/)
console.log(res); // 2
4.split(RegExp|String)
根据正则表达式或字符串将原字符串分割为数组。找不到返回包含原字符串的数组
let str = "hello, world!"
let resArr = str.split(/o/)
console.log(resArr); // ["hell", ", w", "rld!"]
二.字符串使用正则表达式
1.test(String)
判断字符串中是否有满足正则表达式的部分。有,返回true。没有,返回false。
let regT = new RegExp(/el/)
let resT = reg.test(str)
console.log(resT); // true
let regF = new RegExp(/al/)
let resF = reg.test(str)
console.log(resF); // false
2.exec(String)
与match差不多,返回满足表达式的数组。找不到返回null。
let reg = new RegExp(/l/)
let str = "hello, world!"
let res = reg.exec(str)
console.log(res) // ["l", index: 2, input: "hello, world!", groups: undefined]