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


当前回答

卧底C程序员。如果你像我一样想保留首字母缩略词,不想看神秘的模式,那么你可能会喜欢这个:

function isUpperCase (str) {
  return str === str.toUpperCase()
}

export function camelCaseToTitle (str) {
  for (let i = str.length - 1; i > 0; i--) {
    if (!isUpperCase(str[i - 1]) && isUpperCase(str[i])) {
      str = str.slice(0, i) + ' ' + str.slice(i)
    }
  }
  return str.charAt(0).toUpperCase() + str.slice(1)
}

其他回答

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

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

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

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

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


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

试试这个库

http://sugarjs.com/api/String/titleize

'man from the boondocks'.titleize()>"Man from the Boondocks"
'x-men: the last stand'.titleize()>"X Men: The Last Stand"
'TheManWithoutAPast'.titleize()>"The Man Without a Past"
'raiders_of_the_lost_ark'.titleize()>"Raiders of the Lost Ark"

我也遇到过类似的问题,我是这样处理的:

stringValue.replace(/([A-Z]+)*([A-Z][a-z])/g, "$1 $2")

对于更健壮的解决方案:

stringValue.replace(/([A-Z]+)/g, " $1").replace(/([A-Z][a-z])/g, " $1")

http://jsfiddle.net/PeYYQ/

输入:

 helloThere 
 HelloThere 
 ILoveTheUSA
 iLoveTheUSA

输出:

 hello There 
 Hello There 
 I Love The USA
 i Love The USA

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

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')
 })
})