如何模拟window.location.search?

How to mock window.location.search?

我正在尝试从 url 获取参数,但我无法判断它是否有效,因为 localhost:3000 上的 console.log(window.location.search) 给了我 <empty string> 作为值.

我试过这样模拟它,但它 return 和 window.location.search

不一样
const url = 'https://www.google.com/search?client=firefox-b-1-d&q=query+string

const queryString = url.search

console.log(queryString)  // function search()

有没有办法在本地模拟 window.location.search 的行为,这样我就可以确保在部署应用程序之前获得所需的数据?

您可以像这样使用 URL 对象:

const url = new URL('https://www.google.com/search?client=firefox-b-1-d&q=query+string');

const queryString = url.search

console.log(queryString)  // '?client=firefox-b-1-d&q=query+string'

const urlcheck = new URLSearchParams(window.location.search); const querystringVal= urlParams.get('parameter');

请检查这个。

这是一个将文本解析为 URL 的函数,然后您的代码将起作用

function parseURL(url) {
    var parser = document.createElement('a'),
        searchObject = {},
        queries, split, i;
    // Let the browser do the work
    parser.href = url;
    // Convert query string to object
    queries = parser.search.replace(/^\?/, '').split('&');
    for( i = 0; i < queries.length; i++ ) {
        split = queries[i].split('=');
        searchObject[split[0]] = split[1];
    }
    return {
        protocol: parser.protocol,
        host: parser.host,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        searchObject: searchObject,
        hash: parser.hash
    };
}

const url = parseURL('https://www.google.com/search?client=firefox-b-1-d&q=query+string')
const queryString = url.search
console.log(queryString)  // function search()