4lackof 4lackof - 2 months ago 7x
Javascript Question

jQuery - how to use .replace with jQuery obj

I have the following code:

$('.selector.active').each(function() {
$(this).replace(/\s/g, '_');

What is supposed to happen is: each element with
class that has
, replace the white spaces "
" with "

What I am running into is that
does not work with
is a jQuery obj and
is not a jQuery function. I've also tried
this.replace(/\s/g, '_');
but it also err'd...

I am wondering how I can accomplish what I am setting out to do (replace white spaces with underscore for each element with
as the classes). jQuery or plain JS - it doesn't matter.

Thank you.


I'm assuming you want to replace the text inside the element, in which case you need to get and set the text;

$('.selector.active').each(function() {
  $(this).text($(this).text().replace(/\s/g, '_'));

EDIT: Let me break this out a bit so you understand what it's doing

$('.selector.active').each(function() {
  var innerText = $(this).text();
  var replacedText = innerText.replace(/\s/g, '_');
  //now set the new text in the element

The first code I posted just puts it all together.