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?

Ishrat
  • 251
  • 1
  • 6
  • 16

3 Answers3

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.
Taxel
  • 3,859
  • 1
  • 18
  • 40
  • 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. – Ishrat Oct 28 '21 at 13:28
  • For access in `getServerSideProps` take a look at the [docs for the `context` argument](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) - `context.params` and `context.query` should be enough for you, otherwise dig into `context.req` – Taxel Oct 28 '21 at 14:05
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

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.

manuelkruisz
  • 1,142
  • 7
  • 4