正则替换url里的指定部分

如题。

var utm_source = ‘baidu’;
var href = ‘https://www.example.com/?utm_source=aaa-dh&utm_medium=brandzone’;
var href = ‘https://www.example.com/?utm_source=aaa-dh’;
// 如何正则替换utm_source的值aaa-dh为baidu,而且不能影响后面的utm_medium

回复讨论(解决方案)

var utm_source = ‘baidu’;
var href = ‘https://www.example.com/?utm_source=aaa-dh&utm_medium=brandzone’;
//var href = ‘https://www.example.com/?utm_source=aaa-dh’;
alert(href.replace(/utm_source=.+?(&|$)/,’utm_source=’+utm_source+’$1′));

Posted in 未分类

发表评论