javascript - JS 正则表达式 : select only links (a) with attr

标签 javascript html regex

我必须选择具有特定数据属性的链接标签( a )。现在我这样做: /<a.*?data-extra-url=".*?<\/a>/g 。但是...由于某种原因,当我的输入字符串没有任何行 br -> 时,它会导致完全错误的选择,例如:

<div> <br> <a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere1</a></div> wysiwyg<br> <div><a class="popup-wrap-id-1-2-3" href="https://somehost.api/app/id-1-2-3?someparam=sub-id-1-2-3;sub-sub-id-1-2-3">firstImage</a></div> <br> <div>somecontent</div> <div> <span> <div><a data-some-id="456;789" href="https://somehost.api/app/id-4-5-6?someparam=sub-id-4-5-6;sub-sub-1-2-3">second</a></div> <br> </span> also some more content </div> <div> <span> <div><a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere</a></div> rtf<br> </span> <br> </div> </div>

还有一个实例:https://regex101.com/r/JkI3Fu/1

由于某些原因,我的选择中有所有链接,我做错了什么?

结果我想得到:

array = ['<a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere1</a>', '<a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere</a>']
like here: https://regex101.com/r/NiFFXd/1

最佳答案

重要的是,您的正则表达式会查看您在匹配中不想要的内容。像这样使用 ^

<a[^>]*data-extra-url="[^>]*>[^>]*.

应该能解决你的问题

关于javascript - JS 正则表达式 : select only links (a) with attr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58970114/

相关文章:

javascript - 如何根据输入值自动生成行?

javascript - 未捕获的类型错误 : cannot call method 'cookie' of undefined

javascript - 如何封装由 execCommand 创建的图像

javascript - 在元素之前暂停 css 过渡

regex - 用于检查非空值和空字符串的正则表达式

regex - 通过 linq 中的部分字符串区分

javascript - Dymo条码标签打印

javascript - 为什么我的 Ramda 管道功能不能与过滤器一起使用?

javascript - LocalStorage noUiSlider 值 ||重要的! : (

java - 组合多个正则表达式从 : separated string 中提取子字符串