简体   繁体   English

替换不是特定标签的子字符串的子字符串

[英]Replacing substrings that aren't substrings of specific tags

I need to replace key words in the HTML and put a span around them that later will catch a click event. 我需要替换HTML中的关键字,并在它们周围放一个跨度,以后将捕获单击事件。

I get the HTML in string format, and what I tried was to use regular expressions to replace the specific string with the string surrounded by the span. 我得到的是字符串格式的HTML,我尝试使用正则表达式将特定的字符串替换为用span包围的字符串。 And this all works fine, but the problem is it matches with links and other tags. 一切正常,但问题是它与链接和其他标签匹配。 so it surrounds parts of those too if the key word matches in them. 因此,如果关键字匹配的话,它也会包围这些部分。

Code that I used to replace the keywords: 我用来替换关键字的代码:

textToBeChanged = textToBeChanged.replace(new RegExp(keyword, 'ig'), keywordWrappedInSpan)

Is there a way to expand this so that if its in a link or other tag it does not replace it? 有没有一种方法可以扩展它,使其在链接或其他标签中不会被替换? Or maybe some way with JQuery? 还是JQuery的某种方式?

To achieve expected result, use below of splitting string by keyword test 为了达到预期的效果,请使用下面的通过关键字test分割字符串

  1. Split string by word- 'test' 用单词“ test”分割字符串
  2. Check for characters '' and '' 检查字符“”和“”
  3. Update span with word test accordingly 相应地用单词测试更新跨度

working code example 工作代码示例

 var str = '<div> test <a> test </a> </div>' console.log(str.split('test').map(v => { if(v.indexOf('<a>') === -1 && v.indexOf('</a>') === -1){ v = v + '<span>test</span>' }else{ if(v.indexOf('<a>') !== -1){ v = v + 'test' } } return v }).join('')) 

codepen - https://codepen.io/nagasai/pen/rEvvGV?editors=1010 codepen- https: //codepen.io/nagasai/pen/rEvvGV ? editors = 1010

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM