I need to split a string into an array based on several characters and not interrupt the word.
I used this:
var charPerLine = 17;
var regex = new RegExp('^(.{'+charPerLine+'}\\S*\\s+', 'g');
var output = str.replace(regex, "$&@").split(/\s+@/);
The problem with this code is that sometimes I get a string longer than 17 characters if the space was close to the last character.
For instance,
var str = "I want you to do something else instead.";
Gets a breakdown into:
var output = ["I want you to do something", "else instead."]
But the first line contains more than 17 characters, I need to separate it, for example:
var output = ["I want you to do", "something else", "instead."]
It should also work with punctuation and single / double quotes
Any suggestion?
source
share