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/

Share:
24,007
nathanbweb
Author by

nathanbweb

Updated on June 20, 2020

Comments

  • nathanbweb
    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
    nathanbweb about 12 years
    on another post I read that split-join is faster than regex. true?
  • Mathletics
    Mathletics about 12 years
    regex seems like overkill for a character replace.
  • VisioN
    VisioN about 12 years
    @nathanbweb For short strings split and join might be faster, but not for long strings. Arrays need more memory.
  • Sampson
    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.