With text like this:
<div class="element"> <span>N/A, Category</span> </div>
I want to get rid of every occurrence of N/A
.
Here is my attempt:
$('.element span').each(function() { console.log($(this).text()); $(this).text().replace('N/A, ', ''); });
The logged text is the text inside of the span so the selector is okay.
What am I doing wrong here?
If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.
We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
You need to set the text after the replace call:
$('.element span').each(function() { console.log($(this).text()); var text = $(this).text().replace('N/A, ', ''); $(this).text(text); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="element"> <span>N/A, Category</span> </div>
Here's another cool way you can do it (hat tip @Felix King):
$(".element span").text(function(index, text) { return text.replace("N/A, ", ""); });
It should be like this
$(this).text($(this).text().replace('N/A, ', ''))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With