user1038814
user1038814

Reputation: 9647

Replace text in a tag using javascript?

How may I target certain links in list items using Javascript to remove certain characters? For example I have the following code:

<dd class="xments">
    <ul>
        <li><a href="#">"blah blah",</a></li>
        <li><a href="#">"lo lo",</a></li>
        <li><a href="#">"hhe he"</a></li>
    </ul>
</dd>

I wish to remove the " and , for each list item. Please could some one help?

$("a").text(function(_, text) {
    return text.replace('"', '');
    return text.replace(',', '');
});

Doesn't seem to do it for me. How do I target only items in this list and not all a tags in the doc?

Upvotes: 0

Views: 64

Answers (4)

Jaykumar Patel
Jaykumar Patel

Reputation: 27614

Check this Demo jsFiddle

jQuery

$("a").text(function(el, text){
    return text.replace(/[",]/g, ''); 
});

Result

blah blah
lo lo
hhe he

Pattern

/[",]/g

Here I Check RegExr

Upvotes: 0

phylax
phylax

Reputation: 2086

$('a').each(function (i, e) {
  $(e).text($(e).text().replace(/[",]/g, ''))
});

yours with regexp (and additional conditions):

$("dd.xments ul li a").text(function(idx, text) {
  return text.replace(/[",]/g, '');
});

Upvotes: 1

Manwal
Manwal

Reputation: 23816

$(document).ready(function(){

    $('ul li').each(function(){        
        var that = $(this).children();
        var txt = $(that).html();
        txt = txt.replace(/["']/g, '');
        $(that).html(txt.replace(',',''));
    });

});

Fiddle

Upvotes: 0

Brad Faircloth
Brad Faircloth

Reputation: 327

$("a").text(function(_, text) {
    var txt=text.replace('"', '');
    txt=txt.replace(',', '');
    this.innerText=txt;

});

To target only items in your list, add a class to each item. Change $("a") with $("classname")

Upvotes: 0

Related Questions