简体   繁体   English

Javascript 在字符串中添加空行

[英]Javascript Add Empty Line in to string

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.在这里我不起作用的代码。我尝试过,当字符串行高变为 5 或可整除为 5 时,添加空行但不起作用。

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

}
else {
  value = poemValue

}

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.匹配 4 个完整行,然后替换为这 4 个行加上一个空行。

 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 .如果您希望行数来自变量,则插入到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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM