如何僅從字串中替換第二個數字?
實際刺痛:
messages_0_items_0_data_0
所需結果:
messages_0_items_1_data_0
var new_index = 1;
this_input.attr('id', this_input.attr('id').replace(/[0-9] (?!.*[0-9])/, new_index ));
上面的代碼正在改變最后一個數字,而不是像下面這樣的第二個數字:
不好:
messages_0_items_0_data_1
uj5u.com熱心網友回復:
您可以在第 1 組中的第二個數字之前捕獲,然后匹配要替換的第二個數字。
^(\D*\d \D )\d
查看正則運算式演示。
const s = `messages_0_items_0_data_0
messages[0][items][0][data][0]`;
const regex = /^(\D*\d \D )\d /gm;
console.log(s.replace(regex, (m, g1) => `${g1}1`));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/446488.html
標籤:javascript jQuery 正则表达式 代替 多指标
