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


当前回答

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

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'

其他回答

没有副作用的例子。

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

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

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


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

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

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

const camelize = (str) => str
    .split(' ')
    .map(([first, ...theRest]) => (
        `${first.toUpperCase()}${theRest.join('').toLowerCase()}`)
    )
    .join(' ');
HTTPRequest_ToServer-AndWaiting --> HTTP Request To Server And Waiting

function toSpaceCase(str) { return str .replace(/[-_]/g, ' ') /* * insert a space between lower & upper * HttpRequest => Http Request */ .replace(/([a-z])([A-Z])/g, '$1 $2') /* * space before last upper in a sequence followed by lower * XMLHttp => XML Http */ .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3') // uppercase the first character .replace(/^./, str => str.toUpperCase()) .replace(/\s+/g, ' ') .trim(); } const input = 'HTTPRequest_ToServer-AndWaiting'; const result = toSpaceCase(input); console.log(input,'-->', result)

使用JS的String.prototype.replace()和String.prototype.toUpperCase()

const str = "thisIsATestString"; const res = str.replace (/ ^ [a - z] | [a - z] / g (c i) = >(我吗?": "") + c.toUpperCase()); console.log (res);// "This Is A Test String"