[正则]改变URL中的参数值

来源:互联网 发布:左小祖咒 火葬场 知乎 编辑:程序博客网 时间:2024/06/05 15:34

转自:http://zccst.iteye.com/blog/2212989

如果一个URL是:http://www.example.com/index.html?id=100&name=xx&age=20 


希望将name=meinv怎么办? 
Js代码  收藏代码
  1. function getQueryString(name) {  
  2.     var reg = new RegExp("(\\?|^|&|\#)" + name + "=([^&|^#]*)(&|$|#)""i");  
  3.     var r = window.location.search.substr(1).match(reg);  
  4.     if (r != nullreturn unescape(r[2]); return null;  
  5. }  


Js代码  收藏代码
  1. var url = 'http://www.example.com/index.html?id=100&name=xx&age=20';  
  2. function test(key, value){  
  3.     var u = url.replace(/(\\?|^|&|\#)name=([^&|^#]*)(&|$|#)/, "$1"+key+"="+value+"$2");   
  4.     return u;  
  5. }  
  6. var r = test('name''meinv');console.log(r);  
  7. VM792:6 http://www.example.com/index.html?id=100&name=meinvxxage=20  
原创粉丝点击