Sam Willis Sam Willis - 6 months ago 22
Javascript Question

Replace characters in HTML elements

I have some text on a page which I get using a variable:

<p class="category-list-replace">ksadj| lksd| sakdj</p>
<p class="category-list-replace">sdawfe| nekesa</p>
<p class="category-list-replace">opeiuf| elnfele</p>

var list = $('.category-list-replace');


The text is in three different parts, so the variable returns 3 objects. I want to replace any instance of a pipe; "|" with a comma "," instead.

var listnew = list.replace("|", ",");


I'm stuck here though and can't work out how to split the variables so each one can have the character replaced.

Answer

I'd recommend using the text function, for example:

var list = $('.category-list-replace');
list.text(function(i, text) {
    return text.replace(/\|/g, ",")
});

Note this also uses a regular expression (\/|/) with a global flag (g) to replace multiple occurrences of the | character.

$("#go").click(function() {
  var list = $('.category-list-replace');
  list.text(function(i, text) {
    return text.replace(/\|/g, ",")
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="category-list-replace">ksadj| lksd| sakdj</p> 
<p class="category-list-replace">sdawfe| nekesa</p> 
<p class="category-list-replace">opeiuf| elnfele</p>
<button id="go">Replace</go>

Comments