简体   繁体   English

使用javascript正则表达式获取没有html标签的所有单词

[英]get all words without html tags with javascript regex

i try to use an regex expression to get all words without html tags the goal of this is to tag all words with span tags to be capable to get the word when my mouse is over, but keep html initial tags 我尝试使用正则表达式来获取所有没有html标记的单词,其目的是使用span标记来标记所有单词,以便在我的鼠标停留时能够获取该单词,但保留html初始标记

for example this code 例如此代码

<p>hello i'm <b>jesus</b></p>

should become 应该成为

<p><span>hello</span> <span>i'm</span><b><span>jesus<span></b></p>

So, first step for me, is to get all words, without html tags, and then replace it with span 所以,对我来说,第一步是获取所有单词,不带html标签,然后将其替换为span

This is my regex in javascript ([^\\r\\n\\t\\f>< /]+(?!>)) 这是我的JavaScript正则表达式([^ \\ r \\ n \\ t \\ f> </] +(?!>))

But i have some problems with some tags like 但是我对某些标签有一些问题,例如
Live example here 这里的例子

Finally , when my regex will be ok, i will be ok to replace all words by $(this).html($(this).html().replace(reg, "$1")); 最后,当我的正则表达式正常时,我可以用$(this).html($(this).html()。replace(reg,“ $ 1”)))替换所有单词。

thx for your help Maybe there is an other way to do this ... 谢谢您的帮助也许还有另一种方法可以做到这一点...

Use .split() to split the textContent of the element. 使用.split()拆分textContent Array#forEach to iterate array after .split and appendChild to append Element. Array#forEach.splitappendChild之后追加元素以迭代数组。

 var ELEMENT = document.getElementsByTagName('p')[0]; var text = ELEMENT.textContent; ELEMENT.innerHTML = ''; text.split(' ').forEach(function(elem) { var span = document.createElement('span'); span.innerHTML = elem; ELEMENT.appendChild(span); }); 
 span { margin-left: 10px; } 
 <p>hello i'm <b>jesus</b> </p> 

Fiddle Demo 小提琴演示

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

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