JavaScript 正则表达式 : Find a tag and get some attribute values

标签 javascript regex pattern-matching match

我需要按类和一些属性值捕获 html 标签。

我已经解决了第一部分,按类捕获标签( querySelector 应该类似于: 'input.hashtag' ):

<input type="text" value="#tag3" notified="true" class="label-primary hashtag">

所以,我使用这个正则表达式:

/(?=<input[^>]+(?=[\s+class=\"]hashtag[\s+\"]).+)([^>]+>)/g

您可以在此处查看测试 https://regex101.com/r/zY4sH9/6

我需要的是还捕获属性值:valuenofified ,最终得到:

  • 比赛1 <input type="text" value="#tag3" notified="true" class="label-primary hashtag">
  • 比赛2 #tag
  • 比赛3 true

最佳答案

您说过您已经在使用 .querySelector()方法,因此我建议避免使用正则表达式并使用 native DOM 方法。

var element = document.querySelector('input.hashtag'),
    value = element.value,
    notified = element.getAttribute('notified');

同样,如果您想选择input具有 .hashtag 的元素类 value/notified属性,那么您可以简单地使用两个属性选择器 input.hashtag[value][notified] :

var element = document.querySelector('input.hashtag[value][notified]'),
    value = element.value,
    notified = element.getAttribute('notified');
<小时/>

但是,如果您需要使用正则表达式,则以下内容将捕获 valuenotified属性的值无论顺序如何(因为正在使用正向前瞻):

/(<input(?=[^>]*[\s+class=\"]hashtag[\s+\"])(?=[^>]*value=\"([^"]+)\")(?=[^>]*?notified=\"([^"]+)\")[^>]*\>)/

Updated Example

我只是根据您现有的表达式构建的,所以我不需要解释第一部分。

  • (?=[^>]*value=\"([^"]+)\") - 使用捕获组进行正向预测以匹配 value零个或多个非 > 之后的属性值字符。

  • (?=[^>]*?notified=\"([^"]+)\") - 使用捕获组进行正向预测以匹配 notified零个或多个非 > 之后的属性值字符。

捕获组:

第 1 组 - <input type="text" value="#tag3" notified="true" class="label-primary hashtag">

第 2 组 - #tag3

第 3 组 - true

关于JavaScript 正则表达式 : Find a tag and get some attribute values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994532/

相关文章:

javascript - 具有多个路径的 Canvas isPointInPath()

javascript - D365 从另一个 JS 调用函数时出错

python - 搜索字符串中的禁用词

python - 如果在数据帧列中找到则返回字符串的关键字

java - 使用正则表达式如何忽略评论或引用中的特定字符?

ios - 如何匹配两个语音文件并返回是否是同一个词?

javascript - 如果我已经运行了 CoffeeLint,那么运行 JSLint 有什么好处吗?

javascript - Selenium 在 javascript 弹出窗口中查找元素

javascript - 正则表达式;不匹配数字,除非后跟 '/'

r - 如何提取在 R 中一个字符之后和最后一次出现另一个字符之前发生的所有内容?