viery365
viery365

Reputation: 965

Remove Part of a sentence within an Element

I am using wpdiscuz pluggin for WordPress and I want to remove a part of the content of the .wc-comment-title, that is, remove the 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?

Upvotes: 0

Views: 54

Answers (2)

Niklas
Niklas

Reputation: 13135

Couldn't you just replace the trailing text with " Comments"? Like this: https://jsfiddle.net/6o3wha9g/

$('.wc-comment-title').contents().last()[0].textContent=' Comments';

Upvotes: 1

user1106925
user1106925

Reputation:

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>

Upvotes: 2

Related Questions