我需要将以驼峰命名法书写的字母数字字符串转换为常规字符串。我的输入可以是以下任何一个字符串:
var strs = {
input: [
"thisStringIsGood",
"somethingLikeThis",
"a123CapsHere345AndHEREButNOT678Here90End",
"123CapsHere345AndHEREButNOT678Here90e",
"ABCAcryonym",
"xmlHTTPRequest",
"thisDeviceHasA3PrintingService"
],
expectedResult: [
"This String Is Good",
"Something Like This",
"A123 Caps Here345 And HERE But NOT678 Here90 End",
"123 Caps Here345 And HERE But NOT678 Here90 e",
"ABC Acryoynm",
"Xml HTTP Request",
"This Device Has A3 Printing Service"
]
};
在将字符串转换为预期格式后,我正在这样做:
function capSplit(str) {
return str.replace(/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g, function (match, first) {
if (first) match = match[0].toUpperCase() + match.substr(1);
return match + ' ';
})
}
但问题是空格也与数字相加。我需要将字符串 "thisDeviceHasA3Service"
转换为 "This Device Has A3 Printing Service"
但函数 capSplit(str)
给了我This Device Has A 3 Printing Service
我不知道我错过了什么。这是 fiddle
最佳答案
这是我找到的解决方案:
function capSplit(str) {
return str.replace(/([A-Z][a-z])|([a-z][A-Z])|(\d[a-zA-Z])/g, function (g, m1, m2, m3) {
return m1 ? " " + m1 : (m2 ? m2[0] + " " + m2[1] : m3[0] + " " + m3[1]);
}).replace(/^[a-z]/g, function (g) {
return g.toUpperCase();
});
}
主正则表达式匹配每一种需要插入空格的情况,然后函数在需要的地方插入空格
关于javascript - 正则表达式 : Convert a numeric string from camelCase to regular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32688495/