4lackof 4lackof - 3 months ago 15
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
.selector
class that has
.active
, replace the white spaces "
\s
" with "
_
"

What I am running into is that
.replace
does not work with
$(this)
as
$(this)
is a jQuery obj and
.replace
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
.selector.active
as the classes). jQuery or plain JS - it doesn't matter.

Thank you.

Answer

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
  $(this).text(replacedText);
}

The first code I posted just puts it all together.