LoginSignup
0
0

More than 3 years have passed since last update.

[JavaScript] replaceでパターンにマッチした値に対して関数を実行する方法

Last updated at Posted at 2019-05-25

replaceの第2引数に関数を渡すことで実現できる。

渡す関数の第1引き数は、正規表現にマッチした文字列。第2引き数は、キャプチャした対象($n)の値を受け取る。
(以下例だと_cが_matchにcがcaptureに入る)


// スネークケースの文字列をキャメルケースに変換したい
const toCamel = (str) => {
   return str.replace(/_(\w)/g, (_match, capture) => {
    return capture.toUpperCase()
  });
}

toCamel('camel_case') // camelCase

参考
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0