Search for a string name inside object with spaces

11
May 19, 2019, at 11:10 AM

I have an object like this which contain a string name with whitespaces :

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

I search inside my request query for the name in order to get the item object of it, like this :

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

But how should i now search for a string with whitespaces like this :

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

Here is the process of how things work :

if i do not specify a name in the query like this http://localhost:3000?$name=, i get the following :

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

If i specify for example the object with the name admin like this : http://localhost:3000?$name=admin, then i'll get the following :

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

Now what i'm trying to do is to add in the query the name with the whitespaces like this : http://localhost:3000?$name=admin/manage users so that i can retrieve its items as well.

When i try the following code :

  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; 
      }
    });
  });

Everything works fine if there is no whitespaces but once i search for something with whitespaces then i get undefined for the entry.item but once i console log on the entry then i get the name entered decoded .

Answer 1

It'll be URI encoded - use decodeURIComponent to get what you want:

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; }

READ ALSO
Empty return of variable

Empty return of variable

I have this code:

44
How do I host my React App with Namecheap?

How do I host my React App with Namecheap?

So previously I've deployed React Apps on Heroku and Github and never had a problem but now when I try and get a dang app up on Namecheap's hosting I'm having a million problems

31
How to write to different sections of a window using console.log in node.js?

How to write to different sections of a window using console.log in node.js?

I'm wondering if it's possible to write to different sections/portions of a nodejs terminal window when I log output

11
What's the correct/standard practice to authenticate a user after registration?

What's the correct/standard practice to authenticate a user after registration?

I'm trying to authenticate a user after registrationWhat's the correct or standard way to go about it?

13