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


当前回答

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

输入

myCamelCaseSTRINGToSPLITDemo

输出

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


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

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

用1美元2美元代替。

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

其他回答

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

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

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

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

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

这种实现需要考虑连续的大写字母和数字。

function camelToTitleCase(str) { return str .replace(/[0-9]{2,}/g, match => ` ${match} `) .replace(/[^A-Z0-9][A-Z]/g, match => `${match[0]} ${match[1]}`) .replace(/[A-Z][A-Z][^A-Z0-9]/g, match => `${match[0]} ${match[1]}${match[2]}`) .replace(/[ ]{2,}/g, match => ' ') .replace(/\s./g, match => match.toUpperCase()) .replace(/^./, match => match.toUpperCase()) .trim(); } // ----------------------------------------------------- // var testSet = [ 'camelCase', 'camelTOPCase', 'aP2PConnection', 'superSimpleExample', 'aGoodIPAddress', 'goodNumber90text', 'bad132Number90text', ]; testSet.forEach(function(item) { console.log(item, '->', camelToTitleCase(item)); });

预期的输出:

camelCase -> Camel Case
camelTOPCase -> Camel TOP Case
aP2PConnection -> A P2P Connection
superSimpleExample -> Super Simple Example
aGoodIPAddress -> A Good IP Address
goodNumber90text -> Good Number 90 Text
bad132Number90text -> Bad 132 Number 90 Text

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

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

此解决方案也适用于不在[A-Z]范围内的其他Unicode字符。例如:Ä, Ö, Å。

let camelCaseToTitleCase = (s) => (
  s.split("").reduce(
    (acc, letter, i) => (
      i === 0 || console.log(acc, letter, i)
        ? [...acc, letter.toUpperCase()] 
        : letter === letter.toUpperCase()
        ? [...acc, " ", letter]
        : [...acc, letter] 
    ), []
  ).join("")
)

const myString = "ArchipelagoOfÅland"
camelCaseToTitleCase(myString)