Skip to content Skip to sidebar Skip to footer

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 s

Solution 1:

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.

Post a Comment for "How To Split A String At Every N Characters Or To Nearest Previous Space"