• 关于使用JS去除URL中的指定参数问题,js 对url进行某个参数的删除,并返回url


    在网页上找了半天,发现现在的资源实在是少的可怜,而前端尤甚。所以没办法,于是自己花了一些时间写了一个;

     1 /**
     2  * 删除URL中的指定参数
     3  * @param {*} url 
     4  * @param {*} name 
     5  */
     6 function delUrlParams(url, name){
     7   //根据#号拆分
     8   let poundArr = url.split('#')
     9   //?拆分
    10   let questionArr = [] 
    11   if (poundArr) {
    12       //把#接上
    13       poundArr.forEach((element,index) => {
    14           if(index>0){
    15               element = '#'+ element
    16           }
    17 
    18           let tempArr = element.split('?')
    19           if(!tempArr){
    20               return true
    21           }
    22           tempArr.forEach((item, idx) => {
    23               //保留问号
    24               if (idx > 0) {
    25                   item = '?'+item
    26               }
    27               questionArr.push(item)
    28           })
    29       });
    30   }else{
    31       questionArr = url.split('?')
    32       if (questionArr) {
    33           questionArr.forEach((item, idx)  => {
    34               if (idx > 0) {
    35                   item = '?'+item
    36               }
    37           })
    38       }
    39   }
    40 
    41   if(!questionArr){
    42       return  url
    43   }
    44 
    45   //&符号的处理
    46   let andArr = []
    47   questionArr.forEach((item,index) => {
    48       let andIdx = item.indexOf('&')
    49       if (andIdx <= -1) {
    50           andArr.push(item)
    51           return true
    52       } 
    53 
    54       let tempAndArr = item.split('&')
    55       tempAndArr.forEach((ele, idx) => {
    56           if (idx > 0) {
    57               ele = '&' + ele
    58           }
    59           andArr.push(ele)
    60       })
    61   })
    62 
    63 
    64   let newUrl = ''
    65   andArr.forEach(item => {
    66       let nameIndex = item.indexOf(name+'=')
    67       //不拼接要删除的参数
    68       if (nameIndex > -1) {
    69           //保留第一个问号
    70           let questionIdx = item.indexOf('?')
    71           if (questionIdx == 0) {
    72               newUrl += '?'
    73           }
    74           return true
    75       }
    76       newUrl += item
    77   })
    78 
    79   return newUrl.replace(/?&/g,"?")
    80 }
  • 相关阅读:
    留言板
    阿里云ECS 个人博客搭建流程
    安卓包 无崩溃文件的崩溃问题解决
    win10家庭版 远程桌面解决方案
    python int(a/b)和//的区别(转)
    git基本操作
    《代码整洁之道》读后总结
    《人月神话》的观点:是与非?
    小白第一次装机体验
    python2和python3之间的差异和区别
  • 原文地址:https://www.cnblogs.com/eccpig/p/12546710.html
Copyright © 2020-2023  润新知