给出一个包含CamelCase和大写首字母缩写的字符串,例如'ManualABCTask';
如何将它拆分成一个字符串,并且所有单词和首字母缩略词之间都留有空格?
我有以下过程:
let initial = 'ManualABCTask'
//Split on single upper case followed by any number of lower case:
.split(/(['A-Z'][a-z]*)/g)
//the returned array includes empty string entries e.g. ["", "", "Manual", "A", "", "B", "", "C","", "Task", ""] so remove these:
.filter(x => x != '');
//When joining the array, the acronymn uppercase single letters have a space e.g. 'Manual A B C Task' so instead, reduce and add space only if array entry has more than one character
let word = initial.reduce((prevVal,currVal) => {
return (currVal.length == 1) ? prevVal + currVal : prevVal + ' ' + currVal + ' ';
}, '');
这可以完成所需的组合,例如:
但这是完成工作的大量代码,并且肯定可以在初始正则表达式中处理。
我在写问题时进行了试验,并对正则表达式进行了调整,将其简化为一行,有了很大的改进!因此无论如何都要发布解决方案。
我的正则表达式知道效果不是很好,因此可以在尚待改进的地方
答案 0 :(得分:2)
我对JavaScript
几乎一无所知,但我对此不以为然:
let initial = 'ManualABCTask'
initial = initial.replace(/([A-Z][a-z]+)/g, ' $1 ').trim();
答案 1 :(得分:1)
共有2组:从首字母开始,并带有小写字母,从首字母开始,直到下一个字母不是小写:
find = new RegExp(
"(" +
"[A-Z][a-z]+" + // Group starting from head letter with following lowercases
"|" +
"[A-Z]+(?![a-z])" + // Group with head letters until next letter isn't lowercase:
")",
"g"
)
initial = 'ManualABCTask'.split(find)
答案 2 :(得分:0)
如文章所述,已更改为在正则表达式中处理:
initial = 'ManualABCTask'.split(/(['A-Z']{2,99})(['A-Z'][a-z]*)/g).join(' ');
将长度在2到99之间的任何并发的大写字母分组以获取首字母缩写词,并在任意单个大写字母后跟任意数量的小写字母以获取其他单词。加入太空。