views:

470

answers:

2

I have a string: "The quick brown fox jumps over the lazy dogs."

I want to use javascript (possibly with jQuery) to insert a character every n characters. For example I want to call:

var s = "The quick brown fox jumps over the lazy dogs.";
var new_s = UpdateString("$",5);
// new_s should equal "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$"

The goal is to use this function to insert &shy into long strings to allow them to wrap. Maybe someone knows of a better way?

+6  A: 
String.prototype.chunk = function(n) {
    var ret = [];
    for(var i=0, len=this.length; i < len; i += n) {
       ret.push(this.substr(i, n))
    }
    return ret
};

"The quick brown fox jumps over the lazy dogs.".chunk(5).join('$');
// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."
Crescent Fresh
+1 but your semi-colons are a bit on and off ;)
Andy E
@Andy E: heh, they're optional just before a closing `}`. I don't even realize I do that anymore. It's born from a "must conserve every byte" mentality from years before js compressors became standard ;)
Crescent Fresh
+10  A: 

With regex

"The quick brown fox jumps over the lazy dogs.".replace(/(.{5})/g,"$1$")

The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs.$

cheers,

S.Mark
Damn it! Nice regex-fu there. BTW is the last `$` needed in the replacement string?
Crescent Fresh