搜索字符串但忽略标记 [英] Search a string but ignore tag

查看:52
本文介绍了搜索字符串但忽略标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图搜索字符串的出现但是如果它们是锚标记的一部分则不想匹配它们。

Im a trying to search for occurances of a string but dont want to match them if they are part of an anchor tag.

var str = 'hey there. <a href="github.com">github.com/bvaughn</a>';
str.match(/git/gi)

上面的代码匹配两个内部的git href和锚标签的innerHTML。我想忽略第一场比赛。忽略开始和结束标签,但仍然搜索innerHTML。

The above code matches both the git inside href and the innerHTML of the anchor tag. I want to ignore the first match. Ignore the opening and closing tab but still search the innerHTML.

可以通过修改正则表达式来完成吗?我尝试了几种组合,但我只是没有做对。

Can this be done by modifying the regex? I have tried a couple of combinations but Im just not getting it right.

更新

让我解释一下我的实际用例。我正在尝试创建类似于chrome中内置搜索的搜索界面,我们在其中突出显示页面中的文本。为此,我使用了一个反应组件 - react-highlight-words 。这对普通文本完全正常,但我想在突出显示文本之前自动链接文本中的URL。

Let me explain my actual usecase. I am trying to create search interface similar to the built in search in chrome, where we highlight the text occurrences in a page. For this I use a react component - react-highlight-words. This works totally fine for normal text but I want to autolink urls in the text before I highlight them.

在文本中加上标记并将其传递给上面的组件会混淆标记,因为它也匹配其中的字符。所以我希望它能够使用锚标记的开始和结束标记,但考虑其余部分。

Having markup in the text and passing that to the above component messes up the markup as it matches character in it too. So I want it to igore the anchor tag's opening and closing tag but consider the rest.

这是相关匹配发生的地方。我希望我能以某种方式调整正则表达式来忽略锚标记。

This is where the relevant matching happens. I was hoping I could somehow tweak the regex to ignore the anchor tag.

推荐答案

试试这个正则表达式:

var str = 'hey there. <a href="github.com">github.com/bvaughn</a>';
str = str.replace(/<.*>(.*)<\/.*>/g, "$1")
console.log(str);
str.match(/git/gi)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这篇关于搜索字符串但忽略标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆