0

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?

1
  • 2
    return after return won't return Commented Apr 6, 2014 at 17:12

4 Answers 4

1
$('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, '');
});
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, i confused ' and ,
removed ' from the regexp to only replace " and ,
0
$("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")

2 Comments

Just returning txt and letting jQuery handle it instead of setting this.innerText=txt; would be cleaner
@megawac - yours is definitely cleaner, the addition of setting class name helps to address replacing only those in this particular list rather than all links on the page.
0
$(document).ready(function(){

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

});

Fiddle

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.