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


当前回答

基于上面的一个例子,我想出了这个:

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

它适用于我,因为它使用.trim()来处理边缘情况,其中第一个字母是大写的,并且您最终有一个额外的前导空格。

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

其他回答

下面是使用正则表达式演示驼峰大小写字符串到句子字符串的链接。

输入

myCamelCaseSTRINGToSPLITDemo

输出

我的骆驼案例字符串分裂演示


这是一个将驼峰格式转换为句子文本的正则表达式

(?=[A-Z][a-z])|([A-Z]+)([A-Z][a-rt-z][a-z]\*)

用1美元2美元代替。

单击可查看正则表达式的转换

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

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


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

这个对我有用看看这个

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

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

这是我的版本。它在每个小写英文字母后面的大写英文字母之前增加一个空格,如果需要,还会将第一个字母大写:

例如: This IsCamelCase——> This IsCamelCase 这是骆驼案——>这是骆驼案 This IsCamelCase123——>

  function camelCaseToTitleCase(camelCase){
    if (camelCase == null || camelCase == "") {
      return camelCase;
    }

    camelCase = camelCase.trim();
    var newText = "";
    for (var i = 0; i < camelCase.length; i++) {
      if (/[A-Z]/.test(camelCase[i])
          && i != 0
          && /[a-z]/.test(camelCase[i-1])) {
        newText += " ";
      }
      if (i == 0 && /[a-z]/.test(camelCase[i]))
      {
        newText += camelCase[i].toUpperCase();
      } else {
        newText += camelCase[i];
      }
    }

    return newText;
  }

如果你处理的是大写骆驼的情况,这个片段可以帮助你,它还包含一些规格,所以你可以确保它适合你的情况。

export const fromCamelCaseToSentence = (word) =>
  word
    .replace(/([A-Z][a-z]+)/g, ' $1')
    .replace(/([A-Z]{2,})/g, ' $1')
    .replace(/\s{2,}/g, ' ')
    .trim();

和规格:

describe('fromCamelCaseToSentence', () => {
 test('does not fall with a single word', () => {
   expect(fromCamelCaseToSentence('Approved')).toContain('Approved')
   expect(fromCamelCaseToSentence('MDA')).toContain('MDA')
 })

 test('does not fall with an empty string', () => {
   expect(fromCamelCaseToSentence('')).toContain('')
 })

 test('returns the separated by space words', () => {
   expect(fromCamelCaseToSentence('NotApprovedStatus')).toContain('Not Approved Status')
   expect(fromCamelCaseToSentence('GDBState')).toContain('GDB State')
   expect(fromCamelCaseToSentence('StatusDGG')).toContain('Status DGG')
 })
})