Home > Net >  How to split url in reactJs
How to split url in reactJs

Time:07-30

The full url is /login?redirect=shipping. I want to split it into two parts like this - /login?redirect and shipping. I need the second part of the url. that is shipping How can I do this in reactjs??

CodePudding user response:

You can use useSearchParams from react-router-dom v6.

You can also use URLSearchParams (Provided by Browsers)

In your case it would be as follows:

import React from "react";
import { useSearchParams, useLocation } from "react-router-dom";

export const App = () => {
    const [searchParams, setSearchParams] = useSearchParams();
    const { search } = useLocation();

    console.log(searchParams.get("redirect"));

    // if it's more than 1 value for redirect i.e. redirect=shipping&redirect=shipped
    console.log(searchParams.getAll("redirect")); // will return array of value

    // you can use URLSearchParams also by passing search query
    console.log(new URLSearchParams(search).get("redirect"));
    // URLSearchParams is provided by Browser.
    return <div>Search Param</div>;
};

PS: Follow useSearchParams approach if using react and specifically react-router-dom V6 or else go for URLSearchParams

CodePudding user response:

you can use useParams from react-router-dom and destructure it

import {useParams } from 'react-router-dom';

// Get the redirect param from the URL.
let { redirect} = useParams();

CodePudding user response:

use split function as like below

var url="{baseurl}/login?redirect=shipping";
var result=url.split('=')[1];

console.log(result);
  • Related