Skip to content
Advertisement

Javascript Add Empty Line in to string

I’m trying to create a poem mobile app. I want to add an empty line to the string after each pair of four lines. poemValue input is like this.

JavaScript

I’m trying to convert the above string to this with string functions:

JavaScript

Here’s what I’ve tried so far. Add an empty line when the string line height becomes 5 or divisible to 5 but not working.

JavaScript

Advertisement

Answer

I don’t think testing the number of lines in the input is needed at all – you don’t want to conditionally add newlines to the string, you want to always add newlines. Match 4 full lines, then replace with those 4 lines plus an empty line.

JavaScript

If you want the number of lines to come from a variable, then interpolate into a new RegExp.

JavaScript
Advertisement