正規表現のグループ化で、任意の文字だけ取得して文字列を操作したい。
以下例だと、before[123]
の数字の部分を+1したいです。
before[124]
が期待値です。
そして、before
の部分を変数化させたいのですが、それがうまくいきません。
どうすればいいでしょうか?
期待通りの処理になる
javascript
1 const text = 'before[123]'; 2 const rep = text.replace(/before\[([0-9]+)\]/g, function(match, p1) { 3 const increment = Number(p1) + 1; 4 return 'before[' + increment + ']'; 5 }); 6 console.log(rep) // 'before[124]'
期待通りの処理にならない...
javascript
1 const text = 'before[123]'; 2 const base = 'before'; 3 const reg = new RegExp(base + /\[([0-9]+)\]/, 'g'); 4 const rep = text.replace(reg, function(match, p1) { 5 const increment = Number(p1) + 1; 6 return 'before[' + increment + ']'; 7 }); 8 console.log(rep) // 'before[123]'

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/07 09:48