Đỗ Tiến Đỗ Tiến - 10 months ago 84
Javascript Question

Replace id number with regex

Currently I have an id like this:


Now, I want to replace the number after the phrase
with itself + 1. In this case, I want

I tried
at regex101.com, and I am getting stuck here. Any help would be appreciated. Thanks in advance.

Answer Source

If you don't want to use any group and only match the correct 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;