2

I create a dynamic route pages/post/[postname].tsx . and when I send name to the dynamic route the url shows name with url-encode (%20,%E2,...) I want to show name of the url with dash between words. like below url

https://stackoverflow.com/questions/68041539/using-dash-in-the-dynamic-route-name-in-nuxt-js

how can I do this?

Hasan Cheraghi
  • 867
  • 2
  • 11
  • 26

3 Answers3

1

I've used the getStaticPaths method and pass it an object of slugs before. This has worked for me when dealing with a headless CMS'.

export async function getStaticPaths() {
  // Hit API to get posts as JSON
  const posts = await getPosts()

  // Map a new object with just the slugs
  const paths = posts.map((post) => {
    return { params: { slug: post.slug } }
  })

// Return paths 
  return {
    paths: paths,
    fallback: true
  }
}
0

I think I understand the problem, you're trying to use a set of strings with spaces e.g "the fundamentals of starting web development" as path param to achieve something like this https://www.geniushawlah.xyz/the-fundamentals-of-starting-web-development. That will most likely convert your spaces to %20 which is normal. I would have advised you to first use replace() method to change all spaces to hyphen before passing it as param but the replace() method only changes the first space and leave the rest. There are other ways to get rid of the spaces programmatically but may be stressful and not worth it, so I'll advise you use an hyphenated set of strings by default.

If not, try to use a for-loop with the replace() method to change all spaces to hyphens, then pass it as param.

GeniusHawlah
  • 472
  • 5
  • 17
0

For anyone counter this problem I found it after struggle a little bit. So dynamic route in Next js 13 literally take anything. Words %20 in url is default as part of decoding browser where usually change for space like this is a sentence become this%20is%20a%20sentence To change in next js you can use replace function

In folder

/blog/page.tsx


<Link href={/blog/${title.replace(" ","-")}}>  ///change string space to -
 Read more..
</Link>

result

/blog/example-url