Regular Expressions to insert "\r" every n characters in a line and before a complete word (basically a wordwrap feature)

Julian picture Julian · Feb 9, 2010 · Viewed 10.3k times · Source

I'm new to JavaScript and regular expression. I'm trying to automatically format a text document to specific number of characters per line or put a "\r" before the word.

This is functionally similar to Wordwrap found in numerous text editors.

Eg. I want 10 characters per line

Original:My name is Davey Blue.

Modified:My name \ris Davey \rBlue.

See, if the 10th character is a word, it puts that entire word down into a new line.

I'm thinking the following should work to some degree /.{1,10}/ (This should find any 10 characters right?)

Not sure how to go about the rest.

Please help.

Answer

user187291 picture user187291 · Feb 9, 2010

basically

 text = text.replace(/.{1,10} /g, "$&\n")

i'm sure you meant "\n" not "\r"