viery365 viery365 - 7 months ago 11
Javascript Question

Remove Part of a sentence within an Element

I want to remove a part of a sentence within a paragraph with jQuery or JavaScript.

This is the code:

<p class="wc-comment-title">
<span class="wc_header_text_count">4>/span>
"Comments on "Article 1""
</p>


It displays: 4 Comments on "Article 1"

and I would like to make it: 4 Comments

The number of comments and the name of the article change according to the number of comments and the article in question, it is dinamic.

Ex: 3 Comments on "Blog Post 4"

In that case I want it to display : 3 Comments

Is it possible?

Answer

From the wc_header_text_count class, you can use .nextSibling to get the adjacent text node. Text nodes have a number of methods available for manipulating their content, but since you seem to just want to have the text Comments in its place, you can just replace it altogether.

var spans = document.querySelectorAll(".wc_header_text_count")

for (var i = 0; i < spans.length; i++) {
  spans[i].nextSibling.data = " Comments";
}
<p class="wc-comment-title">
<span class="wc_header_text_count">4</span>
"Comments on "Article 1""
</p>

<p class="wc-comment-title">
<span class="wc_header_text_count">3</span>
"Comments on "Blog Post 4""
</p>

If you didn't necessarily want "Comments" but rather wanted the first word without a quotation mark, you could use a regex.

var spans = document.querySelectorAll(".wc_header_text_count")

for (var i = 0; i < spans.length; i++) {
  spans[i].nextSibling.data = 
    spans[i].nextSibling.data.replace(/^\s*"?(\w+)[\s\S]*$/, " $1");
}
<p class="wc-comment-title">
<span class="wc_header_text_count">4</span>
"Comments on "Article 1""
</p>

<p class="wc-comment-title">
<span class="wc_header_text_count">3</span>
"Comments on "Blog Post 4""
</p>