【问题标题】:How to replace spaces in url with + instead of '%20'?如何用 + 而不是 '%20' 替换 url 中的空格?
【发布时间】:2021-05-04 14:54:50
【问题描述】:

我正在尝试将我的参数转换为字符串以发送 api 请求。 但是,我当前的函数将参数中的空格替换为“%20”。如何更改它以将空格更改为+?

示例参数: {名称:“乔·沃尔什”}

当前结果: ...端点?name=joe%20walsh

想要的结果: ...端点?name=joe+walsh

这是我当前的功能

stringifyParams(params: any) {
  return queryString
    .stringify(params)
    .replace(/[^?=&]+=(&|$)/g, '')
    .replace(/&$/, '')
}

【问题讨论】:

  • 只是出于兴趣,为什么您更喜欢使用加号而不是空格的编码值?我认为加号也应该被编码-eso.org/~ndelmott/url_encode.html。有一些 javascript 函数可以处理这个问题。 encodeUriComponentdecodeURIComponent。看developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • ... 返回 encodeUriCompinent(params.stringify())。然后要在服务器上获取原始值,只需使用 decode 函数。
  • @Zach Smith:加号也代表一个空格,但仅限于某些编码,所以除了可读性之外,我想不出一个很好的理由。
  • stackoverflow.com/a/2678602/3114742。有趣的。我不知道。谢谢。

标签: javascript regex url query-string


【解决方案1】:

您可以使用正则表达式将%20 替换为+

将此附加到函数中:

.replace(/%20/g, '+');

【讨论】:

    【解决方案2】:

    首先你应该用 decodeURIComponent 解码你的 url,然后用加号替换空格

    试试这种和平的代码,如果这对你有用,请告诉我)

    const param = "endpoint?name=joe walsh";
    
    console.log(decodeURIComponent(param.replace(" ","+")));
    

    【讨论】:

      猜你喜欢
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多