0

The full URl is /search-results?query=home+floor&categories=All+Categories. I want to split it into two parts like this - /search-results and query=home+floor&categories=All+Categories. I need the second part of the url. How can I do this in reactjs/nextjs or in javascript?

0

3 Answers 3

3

Use window.location to achieve this:

var path = window.location.pathname; //should be /search-result
var queryString = substr(window.location.search, 1); //should be  query=home+floor&categories=All+Categories

EDIT: In Next.js you can also use next/router (in a React component)

import { useRouter } from 'next/router'

// in component
const router = useRouter();
const {pathname, query} = router; //pathname and query are what you are looking for.
Sign up to request clarification or add additional context in comments.

2 Comments

If I want to access like this, it returns me an object as the query part is made of query + category. I need to access the "query=home+floor&categories=All+Categories" part inside the getServerSideProps. So that I can append the part with the baseUrl and can fetch the data from the server.
For access in getServerSideProps take a look at the docs for the context argument - context.params and context.query should be enough for you, otherwise dig into context.req
2

You can simple use the .split() function on the string, splitting by the "?"-character:

let uri = "/search-results?query=home+floor&categories=All+Categories";

let parts = uri.split("?");

let path = parts[0]; // "/search-results"
let query = parts[1]; // "query=home+floor&categories=All+Categories"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Comments

0

When working with locations in next.js applications, it's typically best to use the built-in router hook. While relying on window would work for client-side rendering, you might run into problems when next.js is rendering something on the server-side.

import { useRouter } from 'next/router'

function YourComponent() {
  const router = useRouter()
  const parts = router.asPath.split('?')
  // ...
}

This would give you an array in the paths variable where paths[0] is /search-results and paths[1] contains your query. Depending on your use-case it might, however, be better to just use router.query, which gives you the parsed query part.

The documentation for next/router is actually pretty good.

3 Comments

thank you. But I need to access the query part inside the getServerSideProps function. And hooks can't be accessed there.
Oh, I see. In that case, you'd really have to either split the context.resolvedUrl or use the context.query property.
Thank you. Context.resolvedUrl solved my problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.