0

I have two strings which could be the value of the variable 'url'

s1 = "example.com/s/ref=f1_a2?k=awesome";    //ref tag is at the middle

s2 = "example.com/s?k=underground&ref=b3_a6"; //ref tag is at the end

I need to replace the values of ref with a string 'answer'

Expected output:

s1 = "example.com/s/ref=answer?k=awesome"

s2 = "example.com/s?k=underground&ref=answer"

I tried using the following regex:

const regex = /ref=(\S)\\?/;
url = url.replace(regex, 'answer')

This just replaces the 'ref=' substring. But I would like to replace it's value. And it has to perform the same if the 'ref' is in the middle of the string or at the end.

1

1 Answer 1

1

const regex = /(&?)ref=(\w+)(\?|&)?/gm;
const str = "example.com/s/ref=f1_a2?k=awesome"
const str2= "example.com/s?k=underground&ref=b3_a6";
const subst = `$1ref=answer$3`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
const result2 = str2.replace(regex, subst);

console.log('result for s1 ', result);
console.log('result for s2 ', result2);

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

Comments

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.