正则表达式替换字符串,但不在html标签内 [英] Regex replace string but not inside html tag

查看:91
本文介绍了正则表达式替换字符串,但不在html标签内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用JavaScript代替HTML页面中的一个字符串,但忽略它,如果它在HTML标记中,例如:

I want to replace a string in HTML page using JavaScript but ignore it, if it is in an HTML tag, for example:

<a href="google.com">visit google search engine</a>
you can search on google tatatata...

我想将 google by < b> google< / b> ,但不在这里:

I want to replace google by <b>google</b>, but not here:

<a href="google.com">visit google search engine</a>
you can search on <b>google</b> tatatata...

我试过这个:

I tried with this one:

regex = new RegExp(">([^<]*)?(google)([^>]*)?<", 'i');
el.innerHTML =  el.innerHTML.replace(regex,'>$1<b>$2</b>$3<');

但问题在于:我得到< b> google< / b> < a> 标记内的

but the problem: I got <b>google</b> inside the <a> tag:

<a href="google.com">visit <b>google</b> search engine</a>
you can search on <b>google</b> tatatata...

如何解决此问题?

How can fix this?

推荐答案

你会更好地使用html解析器,而不是正则表达式。我不确定它可以100%可靠地完成。

You'd be better using an html parser for this, rather than regex. I'm not sure it can be done 100% reliably.

这篇关于正则表达式替换字符串,但不在html标签内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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