简体   繁体   English

JavaScript / jQuery:替换部分字符串?

[英]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 . 我想摆脱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/ 这是你的代码工作: http//jsfiddle.net/ZSXb6/


Here's another cool way you can do it (hat tip @Felix King): 这是另一种很酷的方法(帽子提示@Felix King):

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

它应该是这样的

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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