【问题标题】:Search for a string name inside object with spaces在带有空格的对象内搜索字符串名称
【发布时间】:2019-10-05 07:02:08
【问题描述】:

我有一个像这样的对象,其中包含一个带空格的字符串名称:

{
 xxx: "/xxx/",
 name: "string with spaces",
 items: {
  method: "GET",
 }
}

我在我的请求查询中搜索名称以获取它的项目对象,如下所示:

http://localhost:3000?$name=test

但是我现在应该如何搜索带有空格的字符串:

http://localhost:3000?$name=string with spaces

这是事情的运作过程:

如果我没有在查询中指定名称,例如http://localhost:3000?$name=,我会得到以下信息:

[
 {
  name: "admin",
  item: [xxx]
 },
 {
  name: "auth",
  item: [xxx]
 }
]

如果我指定名称为 admin 的对象,例如:http://localhost:3000?$name=admin,那么我将得到以下信息:

[
 {
  name: "manage users",
  items: {}
 },
 {
  name: "Get user`",
  items: {}
 }
]

现在我要做的是在查询中添加带有空格的名称,如下所示:http://localhost:3000?$name=admin/manage users,以便我也可以检索其项目。

当我尝试以下代码时:

  const { $name } = req.query;

  const name = $name.split('/');
  let currentItem = req.doc;

  name.forEach((name) => {
    const decoded = decodeURIComponent(name);
    currentItem.forEach((entry) => { 
      if (entry.name === decoded) {
        currentItem = entry.item; 
      }
    });
  });

如果没有空格,一切正常,但是一旦我搜索带有空格的东西然后i get undefined for the entry.item,但是一旦我控制台登录条目,我就会得到输入的名称解码。

【问题讨论】:

  • 参数将被uri编码,所以做一个uri解码然后搜索名称
  • 当我控制台登录从查询中检索到的名称时,我得到它,因为我真的想要这样 ['admin', 'Remove user'] 但是一旦 url 页面将不会显示任何内容包含空格
  • 确实是这样的编码 uri ?$name=admin/Remove%20user
  • 您能否举例说明输入是什么以及您的预期输出是什么?我没有得到部分“但是一旦 URL 包含空格,页面将不会显示任何内容”
  • 问题是其他人提到的 URI 编码。您不能在网络浏览器的搜索栏中使用空格,因此浏览器会将空格(和其他字符)转换为其他字符。

标签: javascript arrays node.js object ecmascript-6


【解决方案1】:

它将被 URI 编码 - 使用 decodeURIComponent 来获得你想要的:

const encoded = encodeURIComponent("string with spaces");
const decoded = decodeURIComponent(encoded);
console.log(encoded);
console.log(decoded);
.as-console-wrapper { max-height: 100% !important; top: auto; }

【讨论】:

    猜你喜欢
    • 2013-05-18
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多