简体   繁体   中英

JavaScript/jQuery: replace part of string?

With text like this:

<div class="element">
<span>N/A, Category</span>
</div>

I want to get rid of every occurrence of N/A .

Here is my attempt:

$('.element span').each(function() {
        console.log($(this).text());
        $(this).text().replace('N/A, ', '');
    });

The logged text is the text inside of the span so the selector is okay.

What am I doing wrong here?

You need to set the text after the replace call:

$('.element span').each(function() {
        console.log($(this).text());
        var text = $(this).text().replace('N/A, ', '');
        $(this).text(text);
    });

Here's your code working: http://jsfiddle.net/ZSXb6/


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

它应该是这样的

$(this).text($(this).text().replace('N/A, ', ''))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM