here's the situation: I have a paragraph text with let's say 500 characters. Now I'm trying to wrap every 100 characters in span-Tags to have 5 spans with 100 characters each. I'm doing this at the moment with the following regex in JavaScript:
var target = "< 500 characters of example text here >"
var regex = new RegExp(".{1,100}", "g");
var replacement = target.replace(regex, function replace(match) {
return '<span>' + match + '</span>';
});
That works fine, but the problem is that the function is not caring if there's some whitespace or not and breaks the line even inside words. So I tried to rewrite the regular expression by adding a positive lookbehind checking if there's some whitespace:
var regex = new RegExp(".{1,100}(?<=\s)", "g");
It's working with online regex tester / debugger, but my browser throws out that there's a syntax error "invalid regexp group". I searched a while and figured out, that JavaScript maybe does not support positive lookbehinds. I was rewriting the code again, this was the result:
var regex = new RegExp(".{1,100}(?=\s)", "g");
Again it's only working with online regex tester, not in my project. I'm not a pro and can't say regular expressions are something I totally understand. And maybe that's not the best way to solve me problem. But I hope someone can help me a bit with his JavaScript or jQuery acknowledge.
Best, Christian
I would like to propose some improvements to the last version of your regex.
Start the regex from \s*
, the reason will be clear in a moment.
Put .{1,100}
as a capturng group (surrounded with parentheses).
This way, and due to correction in point 1, you can copy only this group,
without initial "white" chars in "continuation" lines.
To properly serve the last chunk, maybe without any trailing space, write the lookahead as an alternative: either a sequence of "white" chars or the end of text.
So the whole regex can be:
\s*(.{1,100})(?=\s+|$)
And of course, as Pointy commented, write backslashes doubled.