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

时间:2022-11-16 21:37:03

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

但我在这里有一些像Live这样的标签有问题

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 ...

为你的帮助thx也许有另一种方法可以做到这一点......

1 个解决方案

#1


0  

Use .split() to split the textContent of the element. Array#forEach to iterate array after .split and appendChild to append Element.

使用.split()拆分元素的textContent。 Array#forEach在.split和appendChild之后迭代数组以追加Element。

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

#1


0  

Use .split() to split the textContent of the element. Array#forEach to iterate array after .split and appendChild to append Element.

使用.split()拆分元素的textContent。 Array#forEach在.split和appendChild之后迭代数组以追加Element。

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