Nathan Campos
Nathan Campos

Reputation: 29507

Trying to .replace() Without Success

I have some lines of HTML code that are like this:

<li><a href="#" class="lstItem">Testing jQuery [First Bracket]</a></li>
<li><a href="#" class="lstItem">Loving jQuery [Second one]</a></li>

I'm trying to replace what's inside the bracket with nothing onLoad, like this:

var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");

But nothing changes. What's wrong and how to correct this?


After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:

oldtext = $item.text,

Upvotes: 0

Views: 165

Answers (4)

jimbo
jimbo

Reputation: 11042

item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)

edit - predicting next problem

The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:

$(".lstItem")
  .each(function(index, item) {

    var
      $item = $(item),
      oldtext = $item.text(),
      match = oldtext.match(/\[(.*?)\]/),
      newtext = oldtext.replace(match[0], '');

    $item.text(newtext);

  });

Upvotes: 8

Mo Valipour
Mo Valipour

Reputation: 13496

this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.

$(".lstItem").each(function() {
   $(this).html(
       $(this).html().replace(/\[(.*)\]/, "")
   );
});

see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/

Upvotes: 1

Mark Coleman
Mark Coleman

Reputation: 40863

Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.

$(".lstItem").text(function(i, text){
    var match = text.match(/\[(.*?)\]/);
    return text.replace(match[0], "");    
});

Simple example on jsfiddle

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78560

also your regex could be simpler.

var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));

Upvotes: 0

Related Questions