split and join with jQuery each to add space after comma
24,007
Solution 1
Of course you can use split
and 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/
Solution 2
you solution is fine, your fiddle is wrong : split(', ')
Solution 3
No reason to split, join, or call .each
. Just modify the text of all .content
elements via a quick regex:
$(".content").text(function(i,v){
return v.replace(/,/g, ", ");
});
Fiddle: http://jsfiddle.net/jonathansampson/uAHBU/
Author by
nathanbweb
Updated on June 20, 2020Comments
-
nathanbweb about 4 years
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.
$('.content').each(function() { var mydata = $(this).text().split(',').join(", "); $(this).text(mydata); });
fiddle: http://jsfiddle.net/ZXgx2
-
nathanbweb about 12 yearson another post I read that split-join is faster than regex. true?
-
Mathletics about 12 yearsregex seems like overkill for a character replace.
-
VisioN about 12 years@nathanbweb For short strings split and join might be faster, but not for long strings. Arrays need more memory.
-
Sampson about 12 years@nathanbweb I did, and I still don't think splitting and joining is wise. It's unnecessary preoptimization at best. There's no reason to create an array only to dissolve it immediately here.