替换javascript中的正则表达式子字符串

时间:2018-08-28 20:25:04

标签: javascript regex

我有两个字符串,它们可能是变量'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

我需要将ref的值替换为字符串“ answer”

预期输出:

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

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

我尝试使用以下正则表达式:

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

这仅替换了'ref ='子字符串。但我想取代它的价值。并且,如果“ ref”位于字符串的中间或结尾,则必须执行相同的操作。

1 个答案:

答案 0 :(得分: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);