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

孤街醉人 提交于 2019-12-05 20:41:38

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!