2

基本前提是我想在另一个字符之后找到一个字符,然后用它的大写等效替换它。我正在寻找比indexOffor 循环更优雅的解决方案。我已经做到了这一点:

'this-is-my-string'.replace(/\-(\w)/,'$1')

这给了我thisismystring,但我想要thisIsMyString。我能做些什么来改变$1它的大写等效项?

4

2 回答 2

3

您可以使用给替换函数作为第二个参数,并且将使用它返回的任何内容:

'this-is-my-string'.replace(/\-(\w)/g, function(_, letter){
    return letter.toUpperCase();
});
于 2012-06-29T00:11:36.763 回答
3

我建议使用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();
于 2012-06-29T00:12:32.797 回答