如何用javascript / jquery替换url参数? [英] How to replace url parameter with javascript/jquery?

查看:199
本文介绍了如何用javascript / jquery替换url参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种有效的方法来做到这一点,但一直无法找到它,基本上我需要的是给定这个url例如:

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://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

我希望能够使用javascript或jquery用另一个值更改 src 参数中的URL,这可能吗?

I'd like to be able to change the URL in the src parameter with another value using javascript or jquery, is this possible?

谢谢提前。

推荐答案

这不是更好的解决方案吗?

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

编辑:

增加了一些清晰度代码并在结果链接中保存'src'

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

$ 1 表示中的第一部分()(即) src = $ 2 代表<$中的第二部分c $ c>()(即)& ,所以这表示你要改变 src之间的值& 。更清楚的是,它应该是这样的:

$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用于替换所有发生的事件:

ADD-ON for replacing all the ocurrences:

如果您有多个具有相同名称的参数,则可以附加到regex全局标志,例如 text.replace(/(src =) 。*?(&)/ g,'$ 1'+ newSrc +'$ 2'); ,这将替换那些具有相同名称的参数的所有值。

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.

这篇关于如何用javascript / jquery替换url参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆