我如何转换字符串既像'helloThere'或'helloThere'到'HelloThere'在JavaScript?


当前回答

或者使用lodash:

lodash.startCase(str);

例子:

_.startCase('helloThere');
// ➜ 'Hello There'

Lodash是一个很好的库,可以为许多日常的js任务提供快捷方式。还有许多其他类似的字符串操作函数,如camelCase, kebabCase等。

其他回答

const text = 'helloThereMister'; const result = text.replace(/([A-Z])/g, " $1"); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); console.log (finalResult);

第一个字母大写——举个例子。注意“$1”中的空格。


当然,如果第一个字母已经大写了,你就有多余的空间可以删除。

或者使用lodash:

lodash.startCase(str);

例子:

_.startCase('helloThere');
// ➜ 'Hello There'

Lodash是一个很好的库,可以为许多日常的js任务提供快捷方式。还有许多其他类似的字符串操作函数,如camelCase, kebabCase等。

上面的答案对我来说都不完美,所以我不得不带着自己的自行车:

function camelCaseToTitle(camelCase) {
    if (!camelCase) {
        return '';
    }

    var pascalCase = camelCase.charAt(0).toUpperCase() + camelCase.substr(1);
    return pascalCase
        .replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
        .replace(/([a-z])([0-9])/gi, '$1 $2')
        .replace(/([0-9])([a-z])/gi, '$1 $2');
}

测试用例:

null => ''
'' => ''
'simpleString' => 'Simple String'
'stringWithABBREVIATIONInside => 'String With ABBREVIATION Inside'
'stringWithNumber123' => 'String With Number 123'
'complexExampleWith123ABBR890Etc' => 'Complex Example With 123 ABBR 890 Etc'

另一个基于RegEx的解决方案。

respace(str) {
  const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
  return str.replace(regex, '$& ');
}

解释

上面的正则表达式由两个相似的部分组成,由OR运算符分开。前半部分:

([A-Z]) -匹配大写字母… (?=[a-z] [a-z]) -后面跟着一个大写字母和小写字母的序列。

当应用于序列FOo时,它有效地匹配它的F字母。

或者第二种情况:

([a-z]) -匹配小写字母… (?=[A-Z]) -后面跟着一个大写字母。

当应用于序列barFoo时,它有效地匹配了它的r字母。

当找到所有替换候选时,最后要做的事情是用相同的字母替换它们,但要使用额外的空格字符。为此,我们可以使用'$& '作为替换,它将解析为一个匹配的子字符串,后面跟着一个空格字符。

例子

const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']

testWords.map(w => w.replace(regex, '$& '))
->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]

我没有尝试每个人的答案,但我修补过的几个解决方案并不能满足我所有的要求。

我想出了一个办法…

export const jsObjToCSSString = (o={}) =>
    Object.keys(o)
          .map(key => ({ key, value: o[key] }))
          .map(({key, value}) =>
              ({
                key: key.replace( /([A-Z])/g, "-$1").toLowerCase(),
                value
              })
          )
          .reduce(
              (css, {key, value}) => 
                  `${css} ${key}: ${value}; `.trim(), 
              '')