Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery: replace part of string?

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?

like image 571
matt Avatar asked May 30 '11 13:05

matt


People also ask

How do you replace part of a string with something else?

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.

How do you replace an element with another in jQuery?

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.

How do I replace a character in a string?

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.


2 Answers

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, ", ""); }); 
like image 74
Andrew Whitaker Avatar answered Sep 22 '22 22:09

Andrew Whitaker


It should be like this

$(this).text($(this).text().replace('N/A, ', '')) 
like image 33
Codler Avatar answered Sep 25 '22 22:09

Codler