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

查看:41
本文介绍了如何用 javascript/jquery 替换 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 代表第二部分在 () (即)& 中,所以这表明您将要更改 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 for replacing all the ocurrences:

如果你有几个同名的参数,你可以附加到正则表达式全局标志,像这样 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天全站免登陆