码迷,mamicode.com
首页 > 其他好文 > 详细

通过正则查找指定内容

时间:2020-01-24 15:49:45      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:fir   reg   通过   push   foo   mat   match   exp   func   

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))

 

通过正则查找指定内容

标签:fir   reg   通过   push   foo   mat   match   exp   func   

原文地址:https://www.cnblogs.com/qjb2404/p/12232246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!