aps*_*ers 74
是(已编辑以支持非小写输入和Unicode):
function camelCase(input) {
return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
return group1.toUpperCase();
});
}
Run Code Online (Sandbox Code Playgroud)
在MDN的"将函数指定为参数"文档中查看有关"替换回调"的更多信息.
回调函数的第一个参数是完全匹配,后续参数是正则表达式中的括号组(在本例中是连字符后面的字符).
另一种使用reduce的方法:
function camelCase(str) {
return str
.split('-')
.reduce((a, b) => a + b.charAt(0).toUpperCase() + b.slice(1));
}
Run Code Online (Sandbox Code Playgroud)
您可以在每个破折号(-)或字符串的开头之后匹配单词字符,或者您可以通过匹配每个单词边界(\b)后面的单词字符来简化:
function camelCase(s) {
return (s||'').toLowerCase().replace(/(\b|-)\w/g, function(m) {
return m.toUpperCase().replace(/-/,'');
});
}
camelCase('foo-bar'); // => 'FooBar'
camelCase('FOo-BaR-gAH'); // => 'FooBarGah'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38861 次 |
| 最近记录: |