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


当前回答

另一个基于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"]

其他回答

试试这个库

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"

好吧,我在这个游戏上晚了几年,但我有一个类似的问题,我想为每一个可能的输入提供一个替换的解决方案。我必须把大部分功劳归功于本帖中的@ZenMaster和本帖中的@Benjamin Udink ten Cate。 代码如下:

var camelEdges = /([A-Z](?=[A-Z][a-z])|[^A-Z](?=[A-Z])|[a-zA-Z](?=[^a-zA-Z]))/g;
var textArray = ["lowercase",
                 "Class",
                 "MyClass",
                 "HTML",
                 "PDFLoader",
                 "AString",
                 "SimpleXMLParser",
                 "GL11Version",
                 "99Bottles",
                 "May5",
                 "BFG9000"];
var text;
var resultArray = [];
for (var i = 0; i < textArray.length; i++){
    text = textArray[i];
    text = text.replace(camelEdges,'$1 ');
    text = text.charAt(0).toUpperCase() + text.slice(1);
    resultArray.push(text);
}

它有三个子句,都使用了lookahead来防止正则表达式引擎消耗太多字符:

[a-z] (?=[a-z] [a-z])查找一个大写字母,后面跟着一个大写字母,然后是小写字母。这将终结像USA这样的缩写词。 [^ a - z](?=[a - z])查找一个非大写字母后跟一个大写字母。这结束了像myWord这样的单词和像99Bottles这样的符号。 [a- za -z](?=[^a- za -z])查找一个字母后面跟着一个非字母。它以像BFG9000这样的符号前的单词结尾。

这个问题在我的搜索结果的顶部,所以希望我可以为其他人节省一些时间!

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

我想出了一个办法…

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

或者使用lodash:

lodash.startCase(str);

例子:

_.startCase('helloThere');
// ➜ 'Hello There'

Lodash是一个很好的库,可以为许多日常的js任务提供快捷方式。还有许多其他类似的字符串操作函数,如camelCase, kebabCase等。

你可以使用这样的函数:

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/。