-4

Im using a script to replace a string of text and adding a class. However, I need to replace, or remove, ONLY the string in question and keeping any other text. How do I do this? In this example i want to remove "EU" but keep any other text on the string.

This is the script Im using at the moment:

$('body').ready(function(){
$( ".productboxArticlenumber:contains('EU')" ).text('newtext').addClass( "eu" ); });
Jerry
  • 1,069
  • 2
  • 13
  • 31
  • Also, please don't open [multiple questions for the same issue](http://stackoverflow.com/questions/27899421/how-do-i-replace-a-certain-word-with-javascript). – André Dion Jan 20 '15 at 14:44

2 Answers2

1

You'll need to use text() with a replacement function to remove EU from all matching elements' contents.

$('document').ready(
  function() {
    $(".productboxArticlenumber:contains('EU')").text(
      function() {
        return $(this).text().replace(/EU/g, "");
      }
    ).addClass("eu");
  }
);
.eu {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="productboxArticlenumber">This one contains "EU", initially.</p>
<p class="productboxArticlenumber">This one does not.</p>
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

I think:

var nodes =$( ".productboxArticlenumber:contains('EU')" );
$.each(nodes, function (index) {
    console.log($(this).text());
    var replaced = $(this).text().replace("EU", "");
    $(this).text(replaced);
    $(this).addClass( "eu" );
});
$( ".productboxArticlenumber:contains('EU')" ).addClass( "eu" );

Should work. Here is the fiddle http://jsfiddle.net/BenoitNgo/1rumbL5c/

Best regards,

Ngob
  • 446
  • 4
  • 11