How to replace url parameter with javascript/jquery?

前端 未结 17 2392
旧时难觅i
旧时难觅i 2020-11-28 04:06

I\'ve been looking for an efficient way to do this but haven\'t been able to find it, basically what I need is that given this url for example:

http://localh         


        
17条回答
  •  时光说笑
    2020-11-28 04:33

    If you are having very narrow and specific use-case like replacing a particular parameter of given name that have alpha-numeric values with certain special characters capped upto certain length limit, you could try this approach:

    urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue);
    

    Example:

    let urlValue = 'www.example.com?a=b&src=test-value&p=q';
    const newValue = 'sucess';
    console.log(urlValue.replace(/\bsrc=[0-9a-zA-Z_@.#+-]{1,50}\b/, 'src=' + newValue));
    // output - www.example.com?a=b&src=sucess&p=q
    

提交回复
热议问题