作者:胡vidalez | 来源:互联网 | 2023-09-23 11:03
我目前正在开发一个项目,其中API吐出一个格式如下的描述:THISISATITLEThisisaparagraph.Thisisanotherparagraph.我想要得到的结果是
我目前正在开发一个项目,其中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,"
").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'));