通过正则查找指定内容

let str = `"foo" and "bar" and "baz"`

//方法一
function select (regExp, str) {
  const matches = []
  while (true) {
    const match = regExp.exec(str)
    if(match === null) break
    matches.push(match[1])
  }
  return matches
}

console.log(select(/"([^"]*)"/g,str))

//方法二
console.log(str.match(/"([^"]*)"/))

//方法三
function select (regExp, str) {
  const matches = []
  str.replace(regExp,function (all, first) {
     matches.push(first)
  })
  return matches
}
console.log(select(/"([^"]*)"/g,str))

//es10 方法四:matchAll
 function select (regExp, str) { const matches = [] for (const match of str.matchAll(regExp)) { matches.push(match[1]) } } console.log(select(/"([^"]*)"/g,str))

猜你喜欢

转载自www.cnblogs.com/qjb2404/p/12232246.html
今日推荐