How to replace url parameter with javascript/jquery?

前端 未结 17 2354
旧时难觅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:45

    Wouldn't this be a better solution?

    var text = 'http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100';
    var newSrc = 'www.google.com';
    var newText = text.replace(/(src=).*?(&)/,'$1' + newSrc + '$2');
    

    EDIT:

    added some clarity in code and kept 'src' in the resulting link

    $1 represents first part within the () (i.e) src= and $2 represents the second part within the () (i.e) &, so this indicates you are going to change the value between src and &. More clear, it should be like this:

    src='changed value'& // this is to be replaced with your original url
    

    ADD-ON for replacing all the ocurrences:

    If you have several parameters with the same name, you can append to the regex global flag, like this text.replace(/(src=).*?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.

提交回复
热议问题