2

I have elements like this all over the page:

<span class="am-product-terms">$49.95 for each 3 months</span>
<span class="am-product-terms">$149.95 for each year</span>

I wanted to remove the the for... part all up to the end. So I did this:

$('.am-product-terms').replace(/for[\s\S]+/, '')

That threw an error so I tried this:

$('.am-product-terms').text().replace(/for[\s\S]+/, '')

This didn't work either.

1 Answer 1

2

.replace() returns modified string it doesn't update existing text. You need to use returned string and reset it to inputs text.

You can use .text(function)

$('.am-product-terms').text(function(_, text){
    return text.replace(/for[\s\S]+/, '');
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. This is the first time I see this. Why the need to return and not in normal cases?
@alexchenco .replace() returns modified string it doesn't update existing text.
So by adding return the existing one is being returned?
@alexchenco, only return is added, I have use overloaded .text() function to set replaced string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.