JavaScript:字符串匹配后返回 anchor 标记

标签 javascript regex string match return-value

我试图在变量中返回并捕获匹配字符串的下一个直接 anchor 标记。我只想获取匹配字符串后面的单个 anchor 标记,而不获取其他任何内容。这就是我被困住的地方。这是代码和jsfiddle。

<body>

<p id="demo">Click the button to display the matches.</p>
<p><strong>Regular Edition of 325</strong></p>
<a href="link1.html">Link 1</a>
<p><strong>Regular Edition of 658</strong></p>
<a href="link2.html">Link 2</a>
<p><strong>Regular Edition of Something Else</strong></p>
<a href="link3.html">Link 3</a>
<p></p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction(){
parseIt = $("p").find("strong").text();
matchIt();
}
function matchIt(){
resIt = parseIt.match(/Regular Edition of 325/);
document.getElementById("demo").innerHTML=resIt;
console.log($(resIt));
}

</script>

</body>

http://jsfiddle.net/pbpyrojust/V86t6/6/

非常感谢任何帮助。如果您需要更多信息,也请告诉我。

最佳答案

如果您想要 anchor 的属性,那么循环遍历“a”标签而不是段落节点会更容易。您可以使用 jQuery 的“prev()”方法来访问前面的“p”并检查其文本是否与您的正则表达式匹配。 http://jsfiddle.net/V86t6/13/

function myFunction(){
  var mtch = new RegExp(/Regular Edition of 325/);
  $('a').each(function () {
    if($(this).prev().find("strong").text().match(mtch)) {
      document.getElementById("demo").innerHTML=$(this).attr("href")
    }
  });
}

请注意,如果 html 发生更改,此代码将会中断。考虑将每个标签/链接包装在 div 中并迭代容器,而不是使用上一个/下一个/最近的等进行遍历。

由于需要纯 JS 版本( http://jsfiddle.net/V86t6/15/ ):

function myFunction(){
  var mtch = /Regular Edition of 325/;
  Array.prototype.forEach.call(
    document.querySelectorAll('p strong'),
    function(strong) {
      if(strong.innerHTML.match(mtch))
        document.getElementById("demo").innerHTML = strong.parentNode.nextElementSibling.href;
    }
  );
}

关于JavaScript:字符串匹配后返回 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22869741/

相关文章:

c++ - 为什么 c++11 正则表达式(libc++ 实现)这么慢?

php - 在php/regex中解析表内容并通过td获取结果

C++:使用 std::string (&str[0]) 作为缓冲区从文件中安全读取?

java - 字符串索引越界异常 : String index out of range: -3

javascript - 标题没有在抽屉导航器中不起作用 react native

javascript - 从ajax调用返回的值未在 Angular js中的 Controller 中设置为变量

javascript - 正则表达式在括号内捕获时忽略括号

java - 无法从 string.xml 获取字符串

javascript - 图像意外地未在 React Native 教程中渲染

javascript - tinyMCE 在全屏模式下默认显示 HTML 代码