我如何转换字符串既像'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)
}

其他回答

另一个基于RegEx的解决方案。

respace(str) {
  const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
  return str.replace(regex, '$& ');
}

解释

上面的正则表达式由两个相似的部分组成,由OR运算符分开。前半部分:

([A-Z]) -匹配大写字母… (?=[a-z] [a-z]) -后面跟着一个大写字母和小写字母的序列。

当应用于序列FOo时,它有效地匹配它的F字母。

或者第二种情况:

([a-z]) -匹配小写字母… (?=[A-Z]) -后面跟着一个大写字母。

当应用于序列barFoo时,它有效地匹配了它的r字母。

当找到所有替换候选时,最后要做的事情是用相同的字母替换它们,但要使用额外的空格字符。为此,我们可以使用'$& '作为替换,它将解析为一个匹配的子字符串,后面跟着一个空格字符。

例子

const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']

testWords.map(w => w.replace(regex, '$& '))
->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]

我认为这可以用reg exp /([a-z]|[a-z] +)([a-z])/g和替换“$1 $2”来完成。

我爱美国的毒品

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

例如: 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;
  }

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

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

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

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