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
x
13
13
1
aaa
2
bbb
3
ccc
4
ddd
5
eee
6
fff
7
ggg
8
hhh
9
jjj
10
kkk
11
lll
12
mmm
13
I’m trying to convert the above string to this with string functions:
JavaScript
1
15
15
1
aaa
2
bbb
3
ccc
4
ddd
5
6
eee
7
fff
8
ggg
9
hhh
10
11
jjj
12
kkk
13
lll
14
mmm
15
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
1
6
1
if (poemValue.split(/rn|r|n/).length % 5) {
2
value = poemValue + poemValue.concat("nn")
3
} else {
4
value = poemValue
5
}
6
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
1
17
17
1
const input = `aaa
2
bbb
3
ccc
4
ddd
5
eee
6
fff
7
ggg
8
hhh
9
jjj
10
kkk
11
lll
12
mmm`;
13
const output = input.replace(
14
/(?:.*r?n){4}/gm,
15
'$&n'
16
);
17
console.log(output);
If you want the number of lines to come from a variable, then interpolate into a new RegExp
.
JavaScript
1
18
18
1
const lines = 4;
2
const input = `aaa
3
bbb
4
ccc
5
ddd
6
eee
7
fff
8
ggg
9
hhh
10
jjj
11
kkk
12
lll
13
mmm`;
14
const output = input.replace(
15
new RegExp(`(?:.*\r?\n){${lines}}`, 'gm'),
16
'$&n'
17
);
18
console.log(output);