删除字符串中包含特定单词的单词

时间:2018-09-27 16:00:58

标签: javascript

我有一个从帖子中摘录的div。

<div class="elementor-post__excerpt">
&lt;div class=”youtube-player” data-id=”VnlwsUoyjYM”&gt;&lt;/div&gt;
“They were going to unplug him.”
“They were going to unplug him,” Joy told us as she recalled why her mom contacted us in February 2015.
Joy’s dad, Odis, had been in a coma for six weeks…      
</div> 

“ elementor-post__excerpt”容器中的所有内容均为文本。

我需要删除“

每个新摘录都将具有一个新的youtube ID,如果其中包含“ youtube-”,则可以删除整个“

”播放器”?

此代码可以检查它是否包含单词,但不确定如果包含某个单词,如何将其集成到删除句子中。

var str = "Hello world";
var substr = "World";
var result = str.indexOf(substr) > -1;

1 个答案:

答案 0 :(得分:0)

因此您可以使用正则表达式进行匹配

var elem = document.querySelector(".elementor-post__excerpt")
var str = elem.textContent.replace(/<div.*class=”youtube-player”.*div>/, '')
elem.textContent = str;
<div class="elementor-post__excerpt">
&lt;div class=”youtube-player” data-id=”VnlwsUoyjYM”&gt;&lt;/div&gt;
“They were going to unplug him.”
“They were going to unplug him,” Joy told us as she recalled why her mom contacted us in February 2015.
Joy’s dad, Odis, had been in a coma for six weeks…      
</div> 

但是匹配HTML和正则表达式的是not the best thing to do