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.

aaa
bbb
ccc
ddd
eee
fff
ggg
hhh
jjj
kkk
lll
mmm

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

aaa
bbb
ccc
ddd

eee
fff
ggg
hhh

jjj
kkk
lll
mmm

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.

if (poemValue.split(/rn|r|n/).length % 5) {
  value = poemValue + poemValue.concat("nn")
} else {
  value = poemValue
}

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.

const input = `aaa
bbb
ccc
ddd
eee
fff
ggg
hhh
jjj
kkk
lll
mmm`;
const output = input.replace(
  /(?:.*r?n){4}/gm,
  '$&n'
);
console.log(output);

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

const lines = 4;
const input = `aaa
bbb
ccc
ddd
eee
fff
ggg
hhh
jjj
kkk
lll
mmm`;
const output = input.replace(
  new RegExp(`(?:.*\r?\n){${lines}}`, 'gm'),
  '$&n'
);
console.log(output);
Advertisement