Padawan
Padawan

Reputation: 113

Replace dynamic value between dynamic characters in Javascript

I have a string between characters like this:

new/set/25/
type/22/set/3/
aa/23/mine/set/9/yous
set/34
/dol/22/mmm/sss/set/23

it has a value pattern like this:

set/{n}

i tried to replace the {n} value using this function:

var pathname = 'new/set/9/'   
pathName = pathName.replace(/(/\//gset/\//g)([0-9]+)/, '$1' + '5';
//expected result = new/set/5/

but it is not working

Upvotes: 2

Views: 206

Answers (3)

Tsubasa
Tsubasa

Reputation: 1429

Try this one.

let pathname = `uid/22/new/set/203/key/90`;
pathname = pathname.replace(/(?<=set\/)\d+(?=\/)/g, 5);

console.log(pathname);

Upvotes: 1

Yves Kipondo
Yves Kipondo

Reputation: 5603

You can use String.prototype.match method to replace all capturing parentheses value by any other result like bellow

let pattern = /set\/(\d+)\/?/;

let chaines = [
  "new/set/25/",
  "type/22/set/3/",
  "aa/23/mine/set/9/yous",
  "set/34",
  "dol/22/mmm/sss/set/23"
];

chaines.map(c => {
  let matches = c.match(pattern);
  console.log(c.replace(matches[1], 5));
});

Upvotes: 1

prasanth
prasanth

Reputation: 22490

Try this regex paterrn (?<=set\/)\d+(?=\/)

Demo

console.log('uid/22/new/set/203/key/90'.replace(/(?<=set\/)\d+(?=\/)/g,'78'))

Upvotes: 0

Related Questions