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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6177200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:34:41  来源:igfitidea点击:

JavaScript/jQuery: replace part of string?

javascriptjqueryreplace

提问by matt

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?

我在这里做错了什么?

回答by Andrew Whitaker

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);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="element">
  <span>N/A, Category</span>
</div>



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, ", "");
});

回答by Codler

It should be like this

应该是这样的

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