我目前正在开发一个项目,其中的 API 吐出格式如下的描述:
THIS IS A TITLE This is a paragraph. This is another paragraph.
我想得到的结果是
THIS IS A TITLE
This is a paragraph
This is another paragraph
我一直在玩一些正则表达式,但很难得到想要的结果,我目前的尝试是在每个大写字母/单词的末尾添加一个换行符。
var myString = "THIS IS A TITLE This is a paragraph of random text. This is another paragraph of random text.";
var myStringFormatted = myString.replace(/([A-Z]+)/g, ",$1").replace(/,/g," <br />").split(",");
是否可以得到想要的结果? (jsfiddle 示例:https://jsfiddle.net/srwwpxh4/1/)
最佳答案
您可以使用积极的前瞻。
它首先查找非单词字符,然后是大写字符和小写字符,并在之前插入换行符。
var r = /\W+(?=[A-Z][a-z])/g,
s = 'THIS IS A TITLE This is a paraGraph. This is another paragraph.';
console.log(s.replace(r, '$&\n'));
关于javascript - 在字符串中的完整大写标题后添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422173/