简体   繁体   English

从字符串javascript中提取多个特定字符

[英]Extract multiple specific characters from string javascript

I have the following innerHTML in element id "word":我在元素 id "word" 中有以下innerHTML:

<span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span

I would like to create a function (wordReverter) that removes all of the tags, leaving in the above example, only the word "hello".我想创建一个删除所有标签的函数(wordReverter),在上面的例子中只留下“hello”这个词。 Any help would be greatly appreciated, thank you!任何帮助将不胜感激,谢谢!

function wordReverter() {
  var word = document.getElementById("word").innerHTML;
  //var rejoinedWord = rejoined word with <span> tags removed
  document.getElementById("word").innerHTML = rejoinedWord;
}

Get the innerText and use it as a new innerHtml like below获取innerText并将其用作新的innerHtml,如下所示

 (function wordReverter() { var word = document.getElementById("word").innerText; document.getElementById("word").innerHTML = word; })()
 <div id="word"> <span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span> </div>

If you have the containing element, you can target it and retrieve it's textContent , otherwise, you can select all the elements of interest and retrieve their content as below:如果你有包含元素,你可以定位它并检索它的textContent ,否则,你可以选择所有感兴趣的元素并检索它们的内容,如下所示:

 function wordReverter() { let letters = document.querySelectorAll('.white,.green') return Array.from(letters).map(l=>l.textContent).join('') } console.log(wordReverter())
 <span class="green">h</span><span class="white">e</span><span class="white">l</span><span class="green">l</span><span class="white">o</span>

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

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