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


当前回答

试试这个库

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

我的分裂案例解决方案的行为方式,我想:

const splitCase = s => !s || s.indexOf(' ') >= 0 ? s :
    (s.charAt(0).toUpperCase() + s.substring(1))
        .split(/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g)
        .map(x => x.replace(/([0-9]+)/g,'$1 '))
        .join(' ')

输入

'a,abc,TheId,TheID,TheIDWord,TheID2Word,Leave me Alone!'
.split(',').map(splitCase)
.forEach(x => console.log(x))

输出

A
Abc
The Id
The ID
The ID Word
The ID2 Word
Leave me Alone!

由于上述函数需要在JS中使用Lookbehind,而目前Safari中还没有实现,因此我重写了实现,以不使用下面的RegEx:

const isUpper = c => c >= 'A' && c <= 'Z'
const isDigit = c => c >= '0' && c <= '9'
const upperOrDigit = c => isUpper(c) || isDigit(c)

function splitCase(s) {
    let to = []
    if (typeof s != 'string') return to
    let lastSplit = 0
    for (let i=0; i<s.length; i++) {
        let c = s[i]
        let prev = i>0 ? s[i-1] : null
        let next = i+1 < s.length ? s[i+1] : null
        if (upperOrDigit(c) && (!upperOrDigit(prev) || !upperOrDigit(next))) {
            to.push(s.substring(lastSplit, i))
            lastSplit = i
        }
    }
    to.push(s.substring(lastSplit, s.length))
    return to.filter(x => !!x)
}

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

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


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