开发者

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

开发者 https://www.devze.com 2022-12-19 13:00 出处:网络
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.

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 ed开发者_Go百科itors.

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.


basically

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

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


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("");


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号