简体   繁体   English

在每个第二期之后添加换行符

[英]Add line-break after each 2nd period

I'm looking for a solution to separate a long JSON string with line-breaks after each 2nd period. 我正在寻找一种解决方案,以在每个第二个周期后用换行符分隔长的JSON字符串。

What's wrong with this regex? 这个正则表达式有什么问题?

var text = 'Lorem ipsum dolor. Consetetur sadipscing elitr. Sed diam nonumy eirmod tempor invidunt';

text.replace(/(\.(\s+))/g, '\$1 <br><br>');

// Expected behaviour
// Lorem ipsum dolor. Consetetur sadipscing elitr. <br><br>Sed diam nonumy eirmod tempor invidunt

// Current behaviour
// Lorem ipsum dolor. <br><br>Consetetur sadipscing elitr. <br><br>Sed diam nonumy eirmod tempor invidunt

The following should work: 以下应该工作:

text.replace(/(\.[^.]*\.)/g, '$1 <br><br>');

The [^.]* will match any number of characters that are not periods, so this regex will match exactly two periods with anything in between them. [^.]*将匹配任意数量的非句点字符,因此此正则表达式将恰好匹配两个句点,中间包含任何句点。

An alternative: 替代:

text.replace(/(.*?\.){2}/g, '$& <br><br>')

This will expect two chunks of text with a period, then replace them with the match followed by line breaks. 这将期望两个文本块带有一个句点,然后将其替换为匹配项,然后再换行。

You could easily play with the number if you feel like making the breaks more sparse. 如果您想让休息时间更稀疏,可以轻松地玩数字游戏。

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

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