首页 > 解决方案 > 如何使用 Javascript 构建所需的参数?

问题描述

例如,我有基本 URL

  let url = "http://localhost:5000";

我想动态地附加一些required URL parameters到这个 URL

但是当我尝试

    var url = new URL(this.url);
    url.searchParams.set('application', 'ib');
    url.searchParams.set('id', '12345');
    console.log('url', url.href);

我明白了

http://localhost:5000/?application=ib&id=12345

但我需要一直得到required params,而不是先查询参数,然后再将参数拆分为&

http://localhost:5000/application=ib&id=12345

有没有办法自动删除?

我知道我可以对字符串进行某种修改,但是是否有一些 js 方法来获取所有时间直接需要的参数?

标签: javascript

解决方案


问题更多在于您正在使用.searchParams(),这意味着查询和查询始终由?URL 的一部分指示。
如果您想更改基本 URL,为什么不这样做呢?

通过更改设置 URLURL.href

let baseUrl = "http://localhost:5000";
let applicationName = 'ib';
let applicationId = '12345';

url = new URL(baseUrl);
url.href += 'application/' + applicationName;
url.href += '/id/' + applicationId;
console.log(url.href); // http://localhost:5000/application/ib/id/12345

// again the alternative URL if "application" and "id" is implied in your URL:
url = new URL(baseUrl);
url.href += applicationName;
url.href += '/' + applicationId;
console.log(url.href); // http://localhost:5000/ib/12345"

推荐阅读