【问题标题】:Applying a transformation to a captured group将转换应用于捕获的组
【发布时间】:2015-07-08 18:47:40
【问题描述】:

我可以对捕获的组应用转换并在 ES5 中执行替换吗?

我想将虚线名称(例如“foo-bar”)转换为驼峰式(例如“fooBar”)。

function camelify(str) {
  return (str.replace(/(\-([^-]{1}))/g, '$2'.toUpperCase()));
}

【问题讨论】:

标签: javascript


【解决方案1】:

'$2'.toUpperCase(),您传入的第二个参数,等同于 '$2',除了删除破折号之外什么都不做。

您正在寻找callback parameter option in replace:

function camelify(str) {
  return str.replace(/-([^-])/g, function(match, $1) {
    return $1.toUpperCase();
  });
}

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多