JS如何提取URL中的参数并以jason格式返回结果

方法一:使用数组循环

  function serilizeUrl(url) {
      var urlObj = {};
      if (/\?/.test(url)) {
        var urlString = url.subString(url.indexOf('?') + 1);
        var urlArray = urlString.split('&');
        for (var i = 0, len = urlArray.length; i < len; i++) {
          var urlItem = urlArray[i];
          var item = urlItem.split('=');
          urlObj[item[0]] = item[1];
        }
        return urlObj;
      }
      return null;
    }

方法二:使用正则表达式和 URLSearchParams 对象

function extractUrlParams(url) {
    const params = {};
    const queryString = url.split('?')[1];
    
    if (queryString) {
        const searchParams = new URLSearchParams(queryString);
        for (let [key, value] of searchParams) {
            params[key] = value;
        }
    }
    
    return JSON.stringify(params);
}

const url = 'https://www.example.com/?name=Alice&age=30';
const extractedParams = extractUrlParams(url);
console.log(extractedParams);

方法三:使用 URLSearchParams 对象的 entries() 方法

function extractUrlParams(url) {
    const params = {};
    const queryString = url.split('?')[1];
    
    if (queryString) {
        const searchParams = new URLSearchParams(queryString);
        for (let [key, value] of searchParams.entries()) {
            params[key] = value;
        }
    }
    
    return JSON.stringify(params);
}

const url = 'https://www.example.com/?name=Alice&age=30';
const extractedParams = extractUrlParams(url);
console.log(extractedParams);

方法四:使用 split() 方法和 reduce() 方法

function extractUrlParams(url) {
    const params = {};
    const queryString = url.split('?')[1];
    
    if (queryString) {
        queryString.split('&').reduce((acc, param) => {
            const [key, value] = param.split('=');
            acc[key] = decodeURIComponent(value);
            return acc;
        }, params);
    }
    
    return JSON.stringify(params);
}

const url = 'https://www.example.com/?name=Alice&age=30';
const extractedParams = extractUrlParams(url);
console.log(extractedParams);

你可能感兴趣的:(前端知识总结,javascript,开发语言,ecmascript,前端,学习)