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


当前回答

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)

其他回答

你可以使用这样的函数:

function fixStr(str) {
    var out = str.replace(/^\s*/, "");  // strip leading spaces
    out = out.replace(/^[a-z]|[^\s][A-Z]/g, function(str, offset) {
        if (offset == 0) {
            return(str.toUpperCase());
        } else {
            return(str.substr(0,1) + " " + str.substr(1).toUpperCase());
        }
    });
    return(out);
}

"hello World" ==> "Hello World"
"HelloWorld" ==> "Hello World"
"FunInTheSun" ==? "Fun In The Sun"

带有一堆测试字符串的代码:http://jsfiddle.net/jfriend00/FWLuV/。

保留前导空格的替代版本:http://jsfiddle.net/jfriend00/Uy2ac/。

我没有尝试每个人的答案,但我修补过的几个解决方案并不能满足我所有的要求。

我想出了一个办法…

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

此解决方案也适用于不在[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)

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

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'

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

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