基本前提是我想在另一个字符之后找到一个字符,然后用它的大写等效替换它。我正在寻找比indexOf
for 循环更优雅的解决方案。我已经做到了这一点:
'this-is-my-string'.replace(/\-(\w)/,'$1')
这给了我thisismystring
,但我想要thisIsMyString
。我能做些什么来改变$1
它的大写等效项?
基本前提是我想在另一个字符之后找到一个字符,然后用它的大写等效替换它。我正在寻找比indexOf
for 循环更优雅的解决方案。我已经做到了这一点:
'this-is-my-string'.replace(/\-(\w)/,'$1')
这给了我thisismystring
,但我想要thisIsMyString
。我能做些什么来改变$1
它的大写等效项?
您可以使用给替换函数作为第二个参数,并且将使用它返回的任何内容:
'this-is-my-string'.replace(/\-(\w)/g, function(_, letter){
return letter.toUpperCase();
});
我建议使用James Robert 的 toCamel 字符串方法。
String.prototype.toCamel = function(){
return this.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};
然后这样称呼它:
'this-is-my-string'.replace(/\-(\w)/,'$1').toCamel();