Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 如何用javascript / jquery替换url参数?(How to replace url parameter with javascript/jquery?)

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:(我一直在寻找一种有效的方法来执行此操作,但是却找不到它,基本上我需要的是给定此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 I'd like to be able to change the URL in the src parameter with another value using javascript or jquery, is this possible?(我希望能够使用javascript或jquery用另一个值更改src参数中的URL,这可能吗?) Thanks in advance.(提前致谢。)   ask by Javier Villanueva translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following solution combines other answers and handles some special cases:(以下解决方案结合了其他答案并处理了一些特殊情况:)

The parameter does not exist in the original url(该参数在原始网址中不存在) The parameter is the only parameter(该参数是唯一的参数) The parameter is first or last(参数是第一个还是最后一个) The new parameter value is the same as the old(新参数值与旧参数值相同) The url ends with a ?(网址以?结尾) character(字符) \b ensures another parameter ending with paramName won't be matched(\b确保不会匹配以paramName结尾的另一个参数) Solution:(解:) function replaceUrlParam(url, paramName, paramValue) { if (paramValue == null) { paramValue = ''; } var pattern = new RegExp('\b('+paramName+'=).*?(&|#|$)'); if (url.search(pattern)>=0) { return url.replace(pattern,'$1' + paramValue + '$2'); } url = url.replace(/[?#]$/,''); return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue; } Known limitations:(已知限制:) Does not clear a parameter by setting paramValue to null, instead it sets it to empty string.(不会通过将paramValue设置为null来清除参数,而是将其设置为空字符串。) See https://stackoverflow.com/a/25214672 if you want to remove the parameter.(如果要删除该参数,请参见https://stackoverflow.com/a/25214672 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...