0

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.

1
  • „but I need a more elegant, legible and efficient solution“ why? Commented Aug 20, 2020 at 8:08

1 Answer 1

2

Using replacer method

let str = "c-fl_1"

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

console.log(res)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.