js 获取正则匹配中间的内容

有一串字符串: '<span class="className">111</span><span class="className">222</span><span class="className">333</span>'
固定格式是'<span class="className">abc</span>'
其中abc可能会有[,\,{ 之类的特殊字符,现在想要匹配111,222,333,abc,该如何获取
const reg = new RegExp('<span class="className">(.+?)</span>', 'g');
str = str.replace(reg, word=>{
   const newReg = new RegExp(keyword,'g')
   replace(newReg, `<span style="color:red;">${keyword}</span>`)
})
这样匹配到的都是完整的字符串,但是我只想要标签之间的内容,并且在标签之间的内容中还要进行二次匹配,匹配某个关键字

你想要的标签之间的内容,是指 111,222,333,abc 这样的吗?

let reg = /<span class="className">(\d+)/g
let ans = []
let matched = null
while ((matched = reg.exec(str)) !== null) {
    ans.push(matched[1]);
}
  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/379292
  • 这篇博客也不错, 你可以看下js获取页面复选框中的值
  • 除此之外, 这篇博客: js闭包在实际开发中的应用中的 总结 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
    • 可以看到,如果外界想访问list变量,只能通过我定义的函数isFirstLoad来进行访问,我对想访问list的外界只提供了isFirstLoad这一个接口。至于怎么操作list,我已经定义好了,外界能做的就只是使用我的函数,然后传几个不同的参数罢了。
    • 最后顺便说一下,作用域链是在定义的时候就已经确定了,和谁来执行,什么时候执行均没有一毛钱关系。
  • 您还可以看一下 搬砖的乔布梭老师的前端面试宝典课程中的 JS面试题21:下拉刷新与上拉加载下一页小节, 巩固相关知识点
  • 以下回答由chatgpt基于相关博客总结生成:

    使用正则表达式的exec方法可以匹配字符串中的一段特定文本,并且返回一个匹配结果数组,其中包括匹配到的文本及相关索引位置等信息。要获取该文本的中间内容,可以使用数组的索引位置信息进行截取。具体步骤如下:

    1. 定义一个正则表达式。 例如,要匹配字符串中的"world":
    const regex = /world/;
    
    1. 使用正则表达式的exec方法对字符串进行匹配。 例如,对字符串"hello world!"进行匹配:
    const matchArray = regex.exec("hello world!");
    
    1. 判断是否匹配成功。 如果匹配成功,matchArray数组的长度大于1;如果匹配失败,matchArray数组的长度为1,且第一个元素为null。 可以使用if语句进行判断:
    if (matchArray && matchArray.length > 1) {
      // 匹配成功,执行下一步操作
    } else {
      // 匹配失败
    }
    
    1. 从匹配结果中提取中间文本。 如果要获取匹配到的"world"的中间文本,可以使用matchArray数组的索引位置信息进行截取:
    const middleText = "hello world!".substring(matchArray.index, matchArray.index + matchArray[0].length);
    

    其中,matchArray.index表示匹配到的文本在原字符串中的起始位置,matchArray[0].length表示匹配到的文本的长度。

    完整代码示例:

    const regex = /world/;
    const matchArray = regex.exec("hello world!");
    if (matchArray && matchArray.length > 1) {
      const middleText = "hello world!".substring(matchArray.index, matchArray.index + matchArray[0].length);
      console.log(middleText); // 输出:world
    } else {
      console.log('匹配失败');
    }