JavaScript/jQuery:替换部分字符串? [英] JavaScript/jQuery: replace part of string?
本文介绍了JavaScript/jQuery:替换部分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
像这样的文字:
<span>N/A,类别</span>
我想摆脱每次出现的N/A
.
这是我的尝试:
$('.element span').each(function() {console.log($(this).text());$(this).text().replace('N/A, ', '');});
记录的文本是跨度内的文本,因此选择器没问题.
我在这里做错了什么?
解决方案
需要设置replace调用后的文字:
$('.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="元素"><span>N/A,类别</span>
这是另一种很酷的方法(帽子提示@Felix King):
$(".element span").text(function(index, text) {return text.replace("N/A, ", "");});
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);
});
<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):
$(".element span").text(function(index, text) {
return text.replace("N/A, ", "");
});
这篇关于JavaScript/jQuery:替换部分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文