Home > Mobile >  Why regex matches when tested but not being captured in String replacement
Why regex matches when tested but not being captured in String replacement

Time:01-08

I am trying to perform the following String replacement via regex.

This is the String.

let originalStr = 'localhost:3000/sample/prospect/card/intl/name?ref=-huNn';

I am replacing the String via following implementation where I am calling 2 different regex replacements on the original string.

// this works 
originalStr = originalStr.replace(`/name`, `/${router.location.query.ref}`); 

// This is the issue. Not replacing. 
// There is an OR in this regex cos I want to replace even if there is no `/card` in the String.
originalStr = originalStr.replace(/\/prospect\/card\/|\/prospect\//, '/prospect/cards/'); 

This is the current updated String.

localhost:3000/sample/prospect/card/intl/-huNn?ref=-huNn

I was expecting it to be the following:

localhost:3000/sample/prospect/cards/intl/-huNn?ref=-huNn // cards instead of card

When tested via https://regex101.com/, the regex is capturing the value correctly.

But in code. the replacement is not happening. What am I doing wrong with this regex?

CodePudding user response:

Your code works.

let originalStr = 'localhost:3000/sample/prospect/card/intl/name?ref=-huNn';

originalStr = originalStr.replace(/\/prospect\/card\/|\/prospect\//, '/prospect/cards/'); 

console.log(originalStr);

Perhaps there is other context to the problem you're seeing, but there's nothing wrong with what you posted.

edit — also your regex could be /\/prospect(\/card)?\//

CodePudding user response:

you may need to use this code in the same line

originalStr = originalStr.replace(/\/prospect\/card\/|\/prospect\//, '/prospect/cards/');

OR use () as

originalStr = ( originalStr
    .replace(/\/prospect\/card\/|\/prospect\//, '/prospect/cards/') ); 

when you didn't use it the javascript interpreter thought the new line is new command

  •  Tags:  
  • Related