javascript 将URL对象转换为URL字符串

hmtdttj4  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(205)

我在localStorage中有一个字符串化的对象

const stringifiedURLObject = fromLocalStorage

我试着用JSON把那个字符串解析成普通的Url Object。我想把这个对象转换成URL字符串

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

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

然后将字符串传递给重定向查询

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

我该怎么做?

xzv2uavs

xzv2uavs1#

你可以用javascript字符串模板轻松做到这一点:

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}`
omhiaaxx

omhiaaxx2#

作为更新,这里有一个解决方案:
https://github.com/vercel/next.js/discussions/22025

import Router from 'next/router';
import { resolveHref } from 'next/dist/shared/lib/router/router';
// for next 13
// import { resolveHref } from 'next/dist/shared/lib/router/utils/resolve-href'

const exampleRoute = {
    pathname: '/work/[slug]',
    query: { 
        slug: 'project-foo',
    },
};
const [, resolvedAs] = resolveHref(Router, exampleRoute, true);
//       ^-- resulting path as a string

**注意:**我测试时``resolveHref的返回类型定义为string,但实际返回的是string[],所以我不得不强制转换为any

相关问题