Home >Web Front-end >JS Tutorial >How to replace url parameters with regular JS

How to replace url parameters with regular JS

php中世界最好的语言
php中世界最好的语言Original
2018-04-12 17:24:202326browse

这次给大家带来JS的正则怎么替换url参数,JS正则替换url参数的注意事项有哪些,下面就是实战案例,一起来看一下。

具体代码如下所示:

/* 定义替换对象键值 */
var setReferArgs = function(){
 var referArgs = new Object();
 referArgs['#userID\#'] = userId;
 referArgs['\#userName\#'] = userName;
 return referArgs;
}
/* 替换URL的参数 */
var replaceUrlParams = function(url){
 var actualUrl = "";
 var referArgs = setReferArgs();
 for(var key in referArgs){
 var e = eval('/'+ key +'/g'); 
 actualUrl = url.replace(e,referArgs[key]);
 url = actualUrl;
 }
 return actualUrl;
}

栗子:

 “http://10.0.0.250:8088/test?uesrID=#userID#” 替换成对应数值 “http://10.0.0.250:8088/test?uesrID=12345”;

 “http://10.0.0.250:8088/test/#userID#” 替换成对应数值 “http://10.0.0.250:8088/12345”;

延伸:

js使用正则表达式从url中获取参数值

//从url中获取参数值
 function getvl(name) {
 var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
 if (reg.test(location.href)) return unescape(RegExp.$2.replace(/\+/g, " "));
 return "";
 };
 var code = getvl("code");

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue改变当前选中项

使用mint-ui时间插件时怎么获取选择值

The above is the detailed content of How to replace url parameters with regular JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn