如何在保留现有HTML的同时将SPAN标记包装到每个单词

时间:2017-03-27 19:49:24

标签: javascript jquery html

说我有这个HTML:

<h2>The standard <strong>Lorem Ipsum</strong> passage, used since the 1500s</h2>

<ul>
  <li>Praesent <strong>vehicula</strong> est id nibh <i>elementum</i> placerat.</li>
</ul>

我需要在保留现有HTML的同时用SPAN包装每个单词。

<h2><span>The</span> <span>standard</span> <strong><span>Lorem</span> <span>Ipsum</span></strong> <span>passage,</span> <span>used</span> <span>since</span> <span>the</span> <span>1500s</span></h2>

<ul>
  <li><span>Praesent</span> <strong><span>vehicula</span></strong> <span>est</span> <span>id</span> <span>nibh</span> <i><span>elementum</span></i> <span>placerat.</span></li>
</ul>

这个JS只适用于文本,但不适用于带有标记的文本。

var fillInText = $('.my-html-editor').html().split(/ +/),
    lenA = fillInText.length,
    resultA = [];

for (var i = 0; i < lenA; i++) {
  resultA[i] = '<span>' + fillInText[i] + '</span>';
}

var joinedText = resultA.join(' ');

console.log(joinedText);

2 个答案:

答案 0 :(得分:2)

替换所有不在<</之前的单词似乎有效:

&#13;
&#13;
var text = document.getElementById("t1").value;
var repl = text.replace(/[\w,\.]+/g, (m, offset, str) => {
  if (str[offset - 1] == "<"
   || str[offset - 2] == "<") return m;
   else return "<span>"+m+"</span>";
});
document.getElementById("t2").value = repl;
&#13;
<textarea id="t1"><h2>The standard <strong>Lorem Ipsum</strong> passage, used since the 1500s</h2>

<ul>
  <li>Praesent <strong>vehicula</strong> est id nibh <i>elementum</i> placerat.</li>
</ul></textarea>
<textarea id="t2"></textarea>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

尝试分享我为此类问题所做的工作。我希望这有助于缩小理解范围。

var x = document.querySelector('#content');
var y = x.textContent.trim().split(" ");
var obj = y.reduce(function(acc, cur, i) {
  cur = cur.replace(/\r?\n|\r/g, "");
  if(cur !== ""){
  	acc[cur] = cur;
  }
  return acc;
}, {});
var regEx=new RegExp(Object.keys(obj).join("|"),"gi");
var newC = x.innerHTML.replace(regEx,function(y){
	return "<span>"+y+"</span>";
})
console.log(newC);
<div id="content">
  <h2>The standard <strong>Lorem Ipsum</strong> passage, used since the 1500s</h2>

  <ul>
    <li>Praesent <strong>vehicula</strong> est id nibh <i>elementum</i> placerat.</li>
  </ul>
</div>