Javascript按小写字符的第一个实例拆分字符串

时间:2018-12-19 17:44:50

标签: javascript regex string split

我想获取Pascal字符串输入,并用连字符分隔。

"HelloWorld" becomes "hello-world"

我能够做到这一点没问题,但是当有人提供以下信息时,我的正则表达式尝试开始崩溃:

"FAQ" becomes "f-a-q"

我希望它将FAQ保留为“常见问题”,所以我认为我需要将所有字符串的首字母小写与大写正确地分开吗?

我的正则表达式现在是:

name.split(/(?=[A-Z])/).join('-').toLowerCase()

1 个答案:

答案 0 :(得分:1)

您可以替换中间的开头大写字母。

function hyphenate(string) {
    return string.replace(/[^A-Z](?=[A-Z])/g, '$&-').toLowerCase();
}

console.log(hyphenate("FAQ"));        // faq
console.log(hyphenate("ReadTheFAQ")); // read-the-faq
console.log(hyphenate("HelloWorld")); // hello-world

相关问题