Home > database >  Turn URL Object into URl string
Turn URL Object into URl string

Time:10-29

So I have a stringified object in my localStorage,

  const stringifiedURLObject = fromLocalStorage 

I tried to JSON.parse that string to normal Url Object. and I want to convert that object into Url string,

  // i want to turn this
  {
    pathname: 'user/[id]'
    query:  {
      mode: 'active'
      id: 'someID'
    }
  }

  // to this
  const normalPathURL = `/user/xxx?mode=active`

Then pass the string to redirect query

  {
    pathname: '/register',
    query: {
      redirect: normalPathURL,
    },
  }

How can i do that?

CodePudding user response:

You can do this easily with javascript string templates:

 const parsedObject = {
    pathname: 'user/[id]'
    query:  {
      mode: 'active'
      id: 'someID'
    }
  }

  // to this
  // parsedObject.pathname.split('/')[0] extracts first part of pathname  
  const normalPathURL = `/${parsedObject.pathname.split('/')[0]}/${parsedObject.query.id}?mode=${parsedObject.query.mode}`
  • Related