Victor Molina
Victor Molina

Reputation: 2661

JavaScript get the last number in a string and replace it with its next

I have this string

let str = "c-fl_1"

and I need to replace the last number '1' with its next '2', so the result string will look like:

"c-fl_2"

Also I need to do that with all the strings which follow this format... For example, the string "c-fl_9102" should change to "c-fl_9103".

Currently I am doing this, and working fine

str = str.replace(new RegExp('\\d+$'), (parseInt(str.match(new RegExp('\\d+$'))) + 1).toString());

but I need a more elegant, legible and efficient solution.

Any ideas? Thank you.

Upvotes: 0

Views: 40

Answers (1)

user8057270
user8057270

Reputation:

Using replacer method

let str = "c-fl_1"

let res = str.replace(new RegExp('\\d+$', 'g'), (match) => +match + 1);

console.log(res)

Upvotes: 2

Related Questions