拆分并加入 jQuery 每个以在逗号后添加空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11102155/
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-26 10:11:22  来源:igfitidea点击:

split and join with jQuery each to add space after comma

jqueryspliteach

提问by nathanbweb

trying to take this content:

尝试获取此内容:

<div class="content">one,two,three</div>
<div class="content">four,five,six</div>
<div class="content">seven,eight,nine</div>

and .split and .join using jQuery's each.

和 .split 和 .join 使用 jQuery 的每个。

$('.content').each(function() {
    var mydata = $(this).text().split(',').join(", ");
    $(this).text(mydata);
});

fiddle: http://jsfiddle.net/ZXgx2

小提琴:http: //jsfiddle.net/ZXgx2

回答by VisioN

Of course you can use splitand join:

当然你可以使用splitand join

$(".content").text(function(i, val) {
    return val.split(",").join(", ");
});

But I'd recommend to use regular expression instead:

但我建议改用正则表达式:

$(".content").text(function(i, val) {
    return val.replace(/,/g, ", ");
});

DEMO:http://jsfiddle.net/ZXgx2/6/

演示:http : //jsfiddle.net/ZXgx2/6/

回答by Rapha?l Althaus

you solution is fine, your fiddle is wrong : split(', ')

你的解决方案很好,你的小提琴是错误的: split(', ')

回答by Sampson

No reason to split, join, or call .each. Just modify the text of all .contentelements via a quick regex:

没有理由拆分、加入或调用.each。只需.content通过快速正则表达式修改所有元素的文本:

?$(".content").text(function(i,v){
    return v.replace(/,/g, ", ");
});??

Fiddle: http://jsfiddle.net/jonathansampson/uAHBU/

小提琴:http: //jsfiddle.net/jonathansampson/uAHBU/