Break a regex line based on number of characters and spaces

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?

+4
source share
2 answers
(?=(\b.{1,17}\b))\1

You can use this and replace it with. $1\nWatch the demo.

https://regex101.com/r/ff7iZp/1

+4

\b , \S*, :

var str = "I want you to do something else instead";

var charPerLine = 15;
var regex = new RegExp('.{'+charPerLine+'}(?:\\b|\\S*\\s+)', 'g');
var output = str.replace(regex, "$&@").split(/\s*@\s*/);

console.log(output);
Hide result
+1

Source: https://habr.com/ru/post/1659018/


All Articles