Home > Enterprise >  How to split URL in reactjs/nextjs
How to split URL in reactjs/nextjs

Time:10-29

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?

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related