Reputation: 6905
I have a string like this : var input = "/first_part/5/another_part/3/last_part"
I want to replace the last occurence of integers (3
in my string), then the first occurence (5
).
I tried this: input .replace(/\d+/, 3);
which replace all occurences. But how to only target the last / first one.
Thanks in advance.
Upvotes: 0
Views: 887
Reputation: 4294
This will replace the first and last single digit in the input string with 3
input.replace(/^(.*?)\d(.*)\d(.*)$/, "$13$23$3");
More readable:
var replacement = '3';
input.replace(/^(.*?)\d(.*)\d(.*)$/, "$1" + replacement + "$2" + replacement + "$3");
or input.replace(/^(.*?)\d(.*)\d(.*)$/, ["$1", "$2", "$3"].join(replacement));
if that's your thing.
Upvotes: 4
Reputation: 3122
Here is a pretty rigid approach to your problem, you might want to adapt it to your needs, but it shows one way you can get things done.
// input string
var string = "/first_part/5/another_part/3/last_part";
//match all the parts of the string
var m = string.match(/^(\D+)(\d+)+(\D+)(\d+)(.+)/);
// ["/first_part/5/another_part/3/last_part", "/first_part/", "5", "/another_part/", "3", "/last_part"]
// single out your numbers
var n1 = parseInt(m[2], 10);
var n2 = parseInt(m[4], 10);
// do any operations you want on them
n1 *= 2;
n2 *= 2;
// put the string back together
var output = m[1] + n1 + m[3] + n2 + m[5];
// /first_part/10/another_part/6/last_part
Upvotes: 0
Reputation: 785146
You can use this negative lookahead based regex:
var input = "/first_part/5/another_part/3/last_part";
// replace first number
var r = input.replace(/\d+/, '9').replace(/\d+(?=\D*$)/, '7');
//=> /first_part/9/another_part/7/last_part
Here \d+(?=\D*$)
means match 1 or more digits that are followed by all non-digits till end of line.
Upvotes: 0