[英]Convert "Sentence case" to "camelCase" in JavaScript
Having a difficult time finding a solution to this, there are several solutions for the reverse.很难找到解决方案,有几种相反的解决方案。
I have considered replacing every " " and the following first character with an uppercase version of itself:我已经考虑将每个“”和以下第一个字符替换为自身的大写版本:
value.toLowerCase().replace(/\s+/g, function (g) { return g[1].toUpperCase() })
Only, the regex /\s+/g needs to be changed to match the first character.只是,正则表达式/\s+/g需要更改以匹配第一个字符。
If there is an existing question that is exactly this, provide link and I will close this myself.如果存在一个正是这样的问题,请提供链接,我将自己关闭它。 I can't find a solution on SO
我在 SO 上找不到解决方案
Examples:例子:
"I walk my dog to the park" or "i Walk my DOG to the Park" => "iWalkMyDogToThePark" “我遛狗去公园”或“我遛狗去公园”=>“iWalkMyDogToThePark”
You need to catch the next character.你需要抓住下一个角色。 You can use (.) or ([az])
您可以使用 (.) 或 ([az])
var toCamelCase = function(string){
return string.replace(/\s+(.)/g, function (match, group) {
return group.toUpperCase()
})
}
Are you looking for something like this:你在寻找这样的东西:
var string = "Hello there what are You doing yes";
string.replace(/([A-Z])([a-z]+)\s+([a-z])([a-z]+)/g, function($1, $2, $3, $4, $5) {
return $2.toLowerCase() + $3 + $4.toUpperCase() + $5;
});
This prints out "helloThere what are youDoing yes"
.这会打印出
"helloThere what are youDoing yes"
。
You can use this camel case conversion code:您可以使用此驼峰转换代码:
function toCamelCase(str) {
return str.replace(/(?:^.|[A-Z]|\b.)/g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '');
}
var val = toCamelCase("Sentence case");
//=> sentenceCase
val = toCamelCase('hello how are you');
//=> helloHowAreYou
I think a simpler solution can be achieved without Regex.我认为没有正则表达式可以实现更简单的解决方案。 Just split the string from spaces, and join them with the appropriate casing.
只需将字符串与空格分开,然后用适当的外壳将它们连接起来。
var value = '...';
var camelCase = value.split(' ').map(function(word, i) {
return (word[0] || '')[i == 0 ? 'toLowerCase' : 'toUpperCase']() +
word.substr(1).toLowerCase();
}).join('');
I ended up doing the following (ES6):我最终做了以下(ES6):
function camelCase (str) {
return str.split(/[^a-zA-Z0-9]/g).map((x, index) => {
if (index === 0) return x.toLowerCase()
return x.substr(0, 1).toUpperCase() + x.substr(1).toLowerCase()
}).join('')
}
It takes the assumption that in general, the aim to convert to camelCase is for variables, so no accents or odd chars should be present (or will be split).它假设通常转换为驼峰式大小写的目的是针对变量,因此不应存在重音或奇数字符(或将被拆分)。
camelCase("I walk my dog to the park")
> "iWalkMyDogToThePark"
function camelCase(sentence){
return sentence.replace("\'","").split(' ').map((item,index) => (index === 0 ? item[0].toLowerCase() : item[0].toUpperCase())+item.substring(1)).join('');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.