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


当前回答

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

我爱美国的毒品

其他回答

或者使用lodash:

lodash.startCase(str);

例子:

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

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

试试这个库

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"

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

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

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

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

好吧,我在这个游戏上晚了几年,但我有一个类似的问题,我想为每一个可能的输入提供一个替换的解决方案。我必须把大部分功劳归功于本帖中的@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这样的符号前的单词结尾。

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