How would you change this:
a-10-b-19-c
into something like this:
a-10-b-20-c
using regular expressions in Javascript?
It should also change this:
a-10-b-19
into this:
a-10-b-20
The only solution I’ve found so far is:
- reverse the original string ->
"c-91-b-01-a" - find the first number (with
\d+) ->"91" - reverse it ->
"19" - turn in into a number (parseInt) ->
19 - add 1 to it ->
20 - turn it into a string again (toString) ->
"20" - reverse it again ->
"02" - replace the original match with this new number ->
"c-02-b-01-a" - reverse the string ->
"a-10-b-20-c"
I was hoping someone on SO would have a simpler way to do this… Anyone?
Here is a simple way.
+str.matchfinds 19, adds 1 to it and returns 20. The+makes sure the answer is an int.str.replacefinds 19 and replaces it with whatstr.matchreturned which was 20.Explanation
(\d*)– matches any digits(?=...)– positive lookahead, doesn’t change regex position, but makes sure that pattern exists further on down the line.(\D*)?$– it doesn’t have to, but can match anything that is not a number multiple times and then matches the end of the string