Home > Enterprise >  Javascript Add Empty Line in to string
Javascript Add Empty Line in to string

Time:08-31

i'm trying to create a poem mobile app. So i just wanna add an empty line into string. poemValue input is like this.

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

i'm trying to convert this string to this with string functions:

aaa
bbb
ccc
ddd

eee
fff
ggg
hhh

jjj
kkk
lll
mmm

here my unworking code.i tried, when the string line height become 5 or divisible to 5, add empty line but not working.

if (poemValue.split(/\r\n|\r|\n/).length % 5) {
    value = poemValue   poemValue.concat("\n\n")

}
else {
  value = poemValue

}

CodePudding user response:

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);

  • Related