What regular expression can I use that sums or subtracts a part of a string?
For instance:I can count to 10!
and it replaces as I can count to 9!
Asked
Active
Viewed 497 times
1

jondiaz
- 160
- 8
-
Regex is not a programming language. You cannot do `1 + 1=2`. – Feb 01 '16 at 21:38
-
@noob You can do simple arithmetic: see here: http://stackoverflow.com/questions/5245087/math-operations-in-regex – jiaweizhang Feb 01 '16 at 21:39
-
1Yes and that uses expressions in perl. I was talking about plain regex. – Feb 01 '16 at 21:41
-
@jiaweizhang perl has some advanced regex functions beyond what javascript has. If you want to do it in javascript, you need write a function to modify the regex match. – Adam Konieska Feb 01 '16 at 21:41
-
My b. Didn't see the js part – jiaweizhang Feb 01 '16 at 21:41
-
You need a callback. Match \d+, in callback subtract 1, then return the itoa. – Feb 01 '16 at 21:45
1 Answers
0
You can use a regex function to change the matched value. Something like this should work:
var str = "I can count to 10!";
str = str.replace(/[0-9]+[0-9]/, function (match, capture) { return match-1;});
console.log(str)
You can see it working here: https://jsfiddle.net/rmtuk3j1/

Adam Konieska
- 2,805
- 3
- 14
- 27
-
4
-
-
It won't work for any number, but the function after the regex helped me! – jondiaz Feb 03 '16 at 18:25