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.
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
来源:https://stackoverflow.com/questions/2232603/regular-expressions-to-insert-r-every-n-characters-in-a-line-and-before-a-com