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


当前回答

连续大写单词的最兼容的答案是:

常量文本 = 'theKD'; const result = text.replace(/([A-Z]{1,})/g, “$1”); const finalResult = result.charAt(0).toUpperCase() + result.slice(1); 控制台.log(最终结果);

它也与KD兼容,不会将其转换为KD。

其他回答

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

我想出了一个办法…

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(), 
              '')

没有副作用的例子。

function camel2title(camelCase) {
  // no side-effects
  return camelCase
    // inject space before the upper case letters
    .replace(/([A-Z])/g, function(match) {
       return " " + match;
    })
    // replace first char with upper case
    .replace(/^./, function(match) {
      return match.toUpperCase();
    });
}

在ES6

const camel2title = (camelCase) => camelCase
  .replace(/([A-Z])/g, (match) => ` ${match}`)
  .replace(/^./, (match) => match.toUpperCase())
  .trim();

或者使用lodash:

lodash.startCase(str);

例子:

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

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

添加了另一个ES6解决方案,我更喜欢上面的一些想法。

https://codepen.io/902Labs/pen/mxdxRv?editors=0010#0

const camelize = (str) => str
    .split(' ')
    .map(([first, ...theRest]) => (
        `${first.toUpperCase()}${theRest.join('').toLowerCase()}`)
    )
    .join(' ');

这个对我有用看看这个

CamelcaseToWord(“名字”);//返回我的名字

    function CamelcaseToWord(string){
      return string.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1");
    }