Đỗ Tiến Đỗ Tiến - 10 days ago 8
Javascript Question

Replace id number with regex

Currently I have an id like this:

s2id_past_example_lashing_guidances_41_commodity_id


Now, I want to replace the number after the phrase
guidances_
with itself + 1. In this case, I want
s2id_past_example_lashing_guidances_41_commodity_id
->
s2id_past_example_lashing_guidances_42_commodity_id


I tried
(s2\w*_)(\d+)(\w*_id)
at regex101.com, and I am getting stuck here. Any help would be appreciated. Thanks in advance.

Answer

If you don't want to use any group and only match the correct id :

\d+(?=_[A-Za-z]+_id$)

Here is an example. It uses a positive lookahead, in order to only find the number which is right before _someword_id.

It makes it easier to replace :

var str = "s2id_past_example_lashing_guidances_41_commodity_id";
var new_str = str.replace(/\d+(?=_[A-Za-z]+_id$)/, function($0) {
  return Number($0)+1;
});
console.log(new_str);