简体   繁体   English

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

[英]Replace regex substring in javascript

I have two strings which could be the value of the variable 'url' 我有两个字符串,它们可能是变量“ 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' 我需要将ref的值替换为字符串“ 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. 这只是替换了'ref ='子字符串。 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. 如果“ ref”在字符串的中间或结尾,则必须执行相同的操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM