美文网首页
js 获取路径路径中参数的值

js 获取路径路径中参数的值

作者: FM_0138 | 来源:发表于2023-12-06 16:03 被阅读0次

    获取路径中参数的值, 并转换为json对象

    使用正则表达式

    function getParamsFromURL(url) {
      const regex = /[?&]([^=#]+)=([^&#]*)/g;
      const params = {};
      let match;
      while (match = regex.exec(url)) {
        params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
      }
      return params;
    }
     
    const url = 'http://example.com?param1=value1&param2=value2';
    const params = getParamsFromURL(url);
    console.log(params); // 输出:{ param1: 'value1', param2: 'value2' }
    
    

    使用URLSearchParams对象

    function getParamsFromURL(url) {
      const searchParams = new URLSearchParams(url.split('?')[1]);
      const params = {};
      for (let param of searchParams) {
        params[param[0]] = param[1];
      }
      return params;
    }
     
    const url = 'http://example.com?param1=value1&param2=value2';
    const params = getParamsFromURL(url);
    console.log(params); // 输出:{ param1: 'value1', param2: 'value2' }
    
    

    相关文章

      网友评论

          本文标题:js 获取路径路径中参数的值

          本文链接:https://www.haomeiwen.com/subject/oypjgdtx.html