Javascript 在带有空格的对象内搜索字符串名称
我有一个像这样的对象,它包含一个带空格的字符串名:Javascript 在带有空格的对象内搜索字符串名称,javascript,arrays,node.js,object,ecmascript-6,Javascript,Arrays,Node.js,Object,Ecmascript 6,我有一个像这样的对象,它包含一个带空格的字符串名: { xxx: "/xxx/", name: "string with spaces", items: { method: "GET", } } 我在我的请求查询中搜索名称,以获取其项对象,如下所示: http://localhost:3000?$name=test http://localhost:3000?$name=string with spaces 但是我现在应该如何搜索带有如下空格的字符串: http://local
{
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=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/manageusers
,这样我也可以检索它的项目
当我尝试以下代码时:
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;
}
});
});
如果没有空格,一切正常,但一旦我搜索带有空格的内容,然后
我就无法定义条目。项目但一旦我登录到条目上,我就可以对输入的名称进行解码。它将被URI编码-使用decodeURIComponent
获取所需内容:
const encoded=encodeURIComponent(“带空格的字符串”);
const decoded=decodeURIComponent(编码);
console.log(编码);
控制台日志(已解码)代码>
.as console wrapper{max height:100%!important;top:auto;}
参数将是uri编码的,因此进行uri解码,然后搜索名称当我在控制台登录从查询中检索到的名称时,我得到了我真正想要的名称['admin','Remove user']但是,一旦url包含空格,页面将不会显示任何内容。这是真的,它是这样一个编码的uri?$name=admin/Remove%20users您可以提供一个输入和预期输出的示例吗?我不明白“但是一旦URL包含空白,页面就不会显示任何内容”这一部分。正如其他人所提到的,问题是URI编码。不能在web浏览器的搜索栏中使用空格,因此浏览器会将空格(和其他字符)转换为其他字符。