views:

286

answers:

4

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.

+2  A: 

I don't think that a regex will do this for you. I would google for javascript wordwrap, I'm sure that someone has written a library to do this for you

phatmanace
+2  A: 

Does it need to be a regular expression? I would do something like this:

var str = "My name is Davey Blue.",
    words = str.split(/(\s+)/);
for (var i=0,n=0; i<words.length; ++i) {
    n += words[i].length;
    if (n >= 10) {
        words[i] = "\n" + words[i];
        n = 0;
    }
}
str = words.join("");
Gumbo
+1  A: 

basically

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

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

stereofrog
Worked like a charm, thanks!
Julian
A: 

This will do the trick with a regular expression.

myString.replace(/((\w|\s){0,9}\s|\w+\s|$)/g, "$1\r")

(Replace "9" by N-1, if N is the desired length of the line)

At each position in the string, this tries to do the following in this order:
1. try to match up to 9 characters greedily (=as many as possible) followed by a space (so in total max. 10 chars ending in a space), then inserts \r after that (by means of a string replacement)
2. if this fails (because no word with less than 10 characters could be found), it matches one word (no matter how long it is) plus a space, then inserts \r after this
3. it matches the end of the string and inserts \r

Mike Warner