ITeye博客

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

zccst · 2015-05-20 20:37 · Web前端-JS语言核心 · Web前端 · JavaScript · Markdown

作者:zccst

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

希望将name=meinv怎么办?


function getQueryString(name) {
	var reg = new RegExp("(\\?|^|&|\#)" + name + "=([^&|^#]*)(&|$|#)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]); return null;
}


var url = 'http://www.example.com/index.html?id=100&name=xx&age=20';
function test(key, value){
	var u = url.replace(/(\\?|^|&|\#)name=([^&|^#]*)(&|$|#)/, "$1"+key+"="+value+"$2"); 
	return u;
}
var r = test('name', 'meinv');console.log(r);
VM792:6 http://www.example.com/index.html?id=100&name=meinvxxage=20

参考:http://www.jb51.net/article/43949.htm

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。