正则表达式:将数字字符串从camelCase转换为常规字符串

时间:2015-09-21 06:15:48

标签: javascript regex

我需要将一个字母数字字符串转换为常规字符串,该字符串是用camelCase编写的。我的输入可以是以下任何字符串:

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

3 个答案:

答案 0 :(得分:4)

这是我找到的解决方案:

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();
  });
}

主正则表达式匹配需要插入空格的所有情况,然后函数插入所需空间

答案 1 :(得分:0)

您可以使用此处https://stackoverflow.com/a/6229124/915194

稍加更改的功能
function capSplit(str) {
    return str
    // insert a space between lower & upper
    .replace(/([a-z])([A-Z])/g, '$1 $2')
    // insert a space between number & any letter
    .replace(/([0-9])([A-Za-z])/g, '$1 $2')
    // space before last upper in a sequence followed by lower
    .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
    // uppercase the first character
    .replace(/^./, function(str){ return str.toUpperCase(); })
}

答案 2 :(得分:0)

答案是,在前瞻中放松了|[0-9],你的代码将起作用

function capSplit(str) {
        return str.replace(/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z])/g, function (match, first) {
            if (first) match = match[0].toUpperCase() + match.substr(1);
            return match + ' ';
        })
    }

此处更新的jsfiddle link