user3451476
user3451476

Reputation: 307

Replace regex substring in javascript

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.

Upvotes: 0

Views: 56

Answers (1)

Muhammad Soliman
Muhammad Soliman

Reputation: 23866

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

Upvotes: 1

Related Questions