arlyxiao / best-practice

1 stars 0 forks source link

Replace url params by regular expression way #6

Open arlyxiao opened 4 years ago

arlyxiao commented 4 years ago
function replaceUrlParams(query, k, v) {
    var re = new RegExp("([?&])" + k + "=.*?(&|$)", "i");
    var separator = query.indexOf('?') === -1 ? '?' : '&';
    if (query.match(re)) {
      return query.replace(re, '$1' + k + "=" + v + '$2');
    }

    return query + separator + k + "=" + v;
}

Test

var query = '?hello1=aa&hello2=bb&hello3=cc';
var newQuery = replaceUrlParams(query, 'hello2', 'mm');

console.log('query: ' + query);
console.log('new query: ' + newQuery);