2

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

3 Answers 3

1

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));
});

Sign up to request clarification or add additional context in comments.

Comments

1

Try this one.

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

console.log(pathname);

2 Comments

how to do it using the replace function , because im plannging to put this 'new/set/{n}' string in the url
@Padawan thanks for your reference, however when i have a string like this: uid/22/new/set/203/key/90 it will become uid/5/new/set/5/key/90 instead of uid/22/new/set/5/key/90
0

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

Demo

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

1 Comment

thanks for your answer, what if the string inside the dynamic url for example if i have string like this uid/22/new/set/203/key/90

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.