如何用 javascript/jquery 替换 url 参数?
我一直在寻找一种有效的方法来做到这一点,但一直找不到它,基本上我需要的是给定这个网址,例如:
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
参数与另一个值一起使用,这可能吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(20)
以下解决方案结合了其他答案并处理一些特殊情况:
?
字符\b
确保另一个以 paramName 结尾的参数不会匹配解决方案:
已知限制:
The following solution combines other answers and handles some special cases:
?
character\b
ensures another parameter ending with paramName won't be matchedSolution:
Known limitations:
如今,使用原生 JS 就可以实现这一点
Nowdays that's possible with native JS
这不是更好的解决方案吗?
编辑:
在代码中增加了一些清晰度,并在生成的链接中保留“src”
$1
表示()
中的第一部分(即)src=
和$2
代表()
中的第二部分(即&
),因此这表明您将更改之间的值>src
和<代码>&。更清楚的是,它应该是这样的:用于替换所有出现的ADD-ON:
如果您有多个同名参数,您可以附加到正则表达式全局标志,就像这样
text.replace(/(src= ).*?(&)/g,'$1' + newSrc + '$2');
这将替换那些共享相同名称的参数的所有值。Wouldn't this be a better solution?
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 betweensrc
and&
. More clear, it should be like this: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.Javascript 现在提供了一个非常有用的功能来处理 url 参数: URLSearchParams
Javascript now give a very useful functionnality to handle url parameters: URLSearchParams
在现代浏览器(除了 IE9 及更低版本的所有浏览器)中,有了 新 URL api
In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api
或者,我们可以使用 pushState() 方法创建一个新历史条目,而不是使用 ReplaceState() 修改当前历史条目:
Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:
这是修改后的 stenix 代码,它并不完美,但它可以处理 url 中包含提供参数的参数的情况,例如:
在这种情况下,searchquery 参数值已更改。
代码:
Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:
In this case searchquery param value is changed.
Code:
如果您有非常狭窄且具体的用例,例如用某些特殊字符替换给定名称的特定参数(其字母数字值上限为一定的长度限制),您可以尝试这种方法:
示例:
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:
Example:
我已经找到了替换 URL 参数的最佳解决方案。
以下函数会将以下 URL 中的房间值替换为 3。
http://example.com/property/? min=50000&max=60000&room=1&property_type=House
http://example.com/property/?min=50000&max=60000&room=3&property_type=House
I have get best solution to replace the URL parameter.
Following function will replace room value to 3 in the following URL.
http://example.com/property/?min=50000&max=60000&room=1&property_type=House
http://example.com/property/?min=50000&max=60000&room=3&property_type=House
编辑参数
URLSearchParams 对象的 set 方法设置参数的新值。
设置新值后,您可以使用 toString() 方法获取新的查询字符串。该查询字符串可以设置为 URL 对象的搜索属性的新值。
然后可以使用 URL 对象的 toString() 方法检索最终的新 url。
来源 - https://usefulangle.com/post/81/javascript-change- url 参数
Editing a Parameter
The set method of the URLSearchParams object sets the new value of the parameter.
After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
The final new url can then be retrieved with the toString() method of the URL object.
Source - https://usefulangle.com/post/81/javascript-change-url-parameters
UpdatE:使它成为一个对你来说很好的功能: http://jsfiddle.net/wesbos/KH25r/1 /
那就去做吧!
UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/
Then go at it!
如果你仔细观察,你会发现关于 URL 的两个令人惊讶的事情:(1) 它们看起来很简单,但细节和极端情况实际上很困难,(2) 令人惊讶的是 JavaScript 没有提供完整的 API 来使使用它们变得更容易。我认为一个成熟的库是为了避免人们自己重新发明轮子或复制一些随机的家伙聪明但可能有错误的正则表达式代码片段。也许尝试 URI.js (http://medialize.github.io/URI.js/ )
If you look closely you'll see two surprising things about URLs: (1) they seem simple, but the details and corner cases are actually hard, (2) Amazingly JavaScript doesn't provide a full API for making working with them any easier. I think a full-fledged library is in order to avoid people re-inventing the wheel themselves or copying some random dude's clever, but likely buggy regex code snippet. Maybe try URI.js (http://medialize.github.io/URI.js/)
我使用这种方法:
返回已删除参数的值
I use this method which:
return the value of the removed parameter
2020 答案,因为我缺少自动删除参数的功能,所以:
基于我最喜欢的答案 https://stackoverflow.com/a /20420424/6284674:
我将其与以下功能结合起来:
''
,则自动删除 URL 参数href="https://stackoverflow.com/a/25214672/6284674">https://stackoverflow.com/a/25214672/6284674
可选地推送直接在window.location中更新的URL bar
IE 支持,因为它仅使用正则表达式,没有 URLSearchParams
JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/
2020 answer since I was missing the functionality to automatically delete a parameter, so:
Based on my favorite answer https://stackoverflow.com/a/20420424/6284674 :
I combined it with the ability to:
automatically delete an URL param if the value if
null
or''
based on answer https://stackoverflow.com/a/25214672/6284674optionally push the updated URL directly in the window.location bar
IE support since it's only using regex and no URLSearchParams
JSfiddle: https://jsfiddle.net/MickV/zxc3b47u/
除了@stenix之外,这对我来说非常有效
这里不需要保存“url”变量,只需替换当前的url
In addition to @stenix, this worked perfectly to me
Here no need to save the "url" variable, just replace in current url
像这样的事情怎么样:
How about something like this:
试试这个
try this
一种没有正则表达式的解决方案,看起来更容易一些,我一直在寻找
它支持端口、哈希参数等。
使用浏览器属性元素作为解析器。
A solution without Regex, a little bit easier on the eye, one I was looking for
This supports ports, hash parameters etc.
Uses browsers attribute element as a parser.
这是用 paramVal 替换 url param 的函数
Here is function which replaces url param with paramVal
一个更长但可能更灵活的答案依赖于两个函数。第一个生成包含所有参数的键/值字典,另一个自行进行替换。这应该适用于旧浏览器,并且还可以在参数不存在时创建该参数。
调用示例:
A lengthier, but maybe more flexible, answer that relies on two functions. The first one produces a key/value dictionary with all the parameters, the other one doing the substitution itself. This should work on old browsers, and can also create the parameter when it doesn't exist.
Exemple of call :