Home > Web Front-end > JS Tutorial > body text

How to replace url parameters with JS regular expression

小云云
Release: 2018-02-26 09:30:55
Original
3037 people have browsed it

本文主要和大家介绍了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;
}
Copy after login

栗子:

“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");
Copy after login

相关推荐:

php正则表达式替换URL链接地址为指定url

php 正则替换url的问题

用javascript替换URL中的参数值示例代码_javascript技巧


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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template