今天遇到一个这样的问题,有一个带参数的url例如:http://www.songchong.comname=songchong&age=24&hometown=hebei&name=songchong&height=180
我们可以看到里面”name=songchong“传个两次,重复了,需要用一段js代码把重复的内容去掉。
这里说一下我的思路,我首先想到了截取字符串和查找字符,但是失败了,原因是indexOf()方法只能返回字符首次出现在字符串中的位置,可是每个参数之间都是用”&“隔开的,这就导致了无法截取。
最后先遍历字符串找出所有”&“的位置,然后截取字符串,拼接字符串,完成任务。
下面是我的代码:
<script>
var url = "http://www.songchong.com?name=songchong&age=24&hometown=hebei&name=songchong&height=180";
var new_url = "";
var new_name_and_value = [];
var where_i = [];
var name_and_value = [];
for(var i=0;i<url.length;i++){
if(url.substring(i-1,i) == "&"||url.substring(i-1,i) == "?"){
where_i.push(i)
}
}
name_and_value.push(url.substring(where_i[where_i.length-1],url.length));
for(var j=0;j<where_i.length-1;j++){
name_and_value.push(url.substring(where_i[j],where_i[j+1]-1))
}
name_and_value.forEach(function(data){
if(new_name_and_value.indexOf(data) == -1){
new_name_and_value.push(data)
}
});
new_url = url.substring(0,where_i[0]);
new_name_and_value.forEach(function(value){
new_url = new_url+value+"&"
});
new_url = new_url.substring(0,new_url.length-1);
console.log(new_url)
</script>
本文介绍了一种使用JavaScript来去除URL中重复参数的方法。通过遍历字符串并记录每个参数出现的位置,确保每个参数只被保留一次。最终生成新的URL,并打印输出。
560

被折叠的 条评论
为什么被折叠?



