user10045300
user10045300

Reputation: 427

How to split a string at every n characters or to nearest previous space

I want to insert a newline character at every 15 characters including spaces.

I'm currently using the regex below which is working to some extent but it is taking me the nearest space after the word and I want the nearest previous space. Any ideas?

const split = str.replace(/([\s\S]{15}[^ ]*)/g, '$1\n');

Any ideas anyone?

Upvotes: 2

Views: 2703

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may use

s.replace(/[\s\S]{1,15}(?!\S)/g, '$&\n')

See the regex demo

Details

  • [\s\S]{1,15} - any 1 to 15 chars, as many as possible (that is, all 15 are grabbed at once and then backtracking occurs to find...)
  • (?!\S) - a position not immediately followed with a non-whitespace (so a whitespace or end of string).

Note that there is no need to wrap the whole pattern with (...) since you may refer to the whole match with a $& placeholder from the replacement pattern.

Upvotes: 4

Related Questions