简体   繁体   中英

Replace the last and first integers of a string

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.

This will replace the first and last single digit in the input string with 3

input.replace(/^(.*?)\\d(.*)\\d(.*)$/, "$13$23$3");

Here's a reFiddle link that demos this: http://refiddle.com/1am9

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM