Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert a character after every n characters in javascript?

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?

like image 801
brendan Avatar asked Nov 20 '09 20:11

brendan


People also ask

Can we use \n in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

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,

like image 125
YOU Avatar answered Oct 07 '22 07:10

YOU


function chunk(str, n) {     var ret = [];     var i;     var len;      for(i = 0, len = str.length; i < len; i += n) {        ret.push(str.substr(i, n))     }      return ret };  chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$'); // "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs." 
like image 33
Crescent Fresh Avatar answered Oct 07 '22 05:10

Crescent Fresh