Using JavaScript's split() Method

Scenario

Most websites nowadays send password reset links to their users' emails. The user clicks on a tokenized link and they are redirected to a new page with a form to enter and confirm their new password. This token is usually generated in the server after a user submits their email. Let's imagine the redirect link looks like so:

https://example.com/auth/set-new-password/65c2b0c961f84712625ec38

As a frontend developer, you need to extract this token (which is the last part of our URL). Think about it for a minute. For now, let's dive into what split() method is and we'll see if it can be used in our scenario.

What is the split() method?

Definition

According to MDN, the split() method is a method that takes a string and divides it into sub-strings. The sub-strings are returned inside an array. The sub-strings are usually ordered. The method uses a pattern given by the user. This pattern usually describes the point at which the split is to occur and acts as the separator.

The split() method also takes an optional limit. This is a non-negative integer that specifies the number of substrings to include in our returned array. In the event that the limit is set to 0, an empty array is returned.

Examples

Suppose you have the following string:

let strOne = 'I fell asleep before pushing my code';

// Our aim for strOne is to return an array of each word, and maybe pick the word 'asleep' out of it.
const arrOne = strOne.split(' ');
// arrOne = ['I', 'fell', 'asleep', 'before', 'pushing', 'my', 'code']
let word = arrOne[2];
// word = 'asleep'

// The shorthand for our problem can be written like so:
word = strOne.split(' ')[2];
// word = 'asleep'

// Using a limit
const arrLimit = strOne.split(' ', 5)
// arrLimit = 'pushing'
const arrLimitZero = strOne.split(' ', 0)
// arrLimitZero = []

In this example we are using split() and passing an empty string as a separator. The string strOne has seven words separated by spaces (which in programming are empty strings). By issuing the method with the empty string pattern, we are able to return arrOne. Since we want to also return the word asleep, we pass a bracket notation with the index of the specific element we want to access. This is index 2.

Back to our Scenario

Assuming we are building a React application and are interested in the accessing our URL that has the token. Using react-router we are able to call the useLocation() hook.

First, we will need to install our dependencies:

yarn add react-router

With this package, we should be able to access useLocation().

The next step will be to import the hook inside our component.

// import hook at the top of your component
import { useLocation } from 'react-router'

Using useLocation() it is possible to access our current URL by accessing the pathname property that is built inside the hook. Through destructuring it's possible to access the various objects built inside useLocation() such as pathname, search, key, hash, and state.

const { pathname } = useLocation()
console.log(pathname)
// 'https://example.com/auth/set-new-password/65c2b0c961f84712625ec38'

Now that we have access to the URL, we can figure out how to access its last part. Let's do an inspection of the string that is returned in the pathname:

  • it has the forward slash /.

  • the forward slashes separates each part of the URL

With this info in mind, we can see why the split() method is a straightforward solution to accessing our token.

Solution

First let's divide the URL into sub-strings and see what is returned inside our new array. Secondly, we will access the token by passing the appropriate index position.

const urlArr = pathname.split('/')
console.log(urlArr)
// ["https:", "", "example.com", "auth", "set-new-password", "65c2b0c961f84712625ec38"]
const token = urlArr[5]
console.log(token)
// "65c2b0c961f84712625ec38"

We pass the / as our separator and in so doing, the method creates a sub-string each time it encounters the pattern. Our array does have 6 elements/sub-strings. In order to access the token we pass its position by using bracket notation. Now that we have accessed the token, we can use within our component as needed. Below is a simple example of how the token extraction will look in the component.


import React from 'react';
import { useLocation } from 'react-router';

function ResetPasswordForm() {
    const { pathname } = useLocation();
    const token = pathname.split('/')[5];

    return (
        <div>
            {/*Your code for form inputs*/}
        </div>
    )
}

export default ResetPasswordForm;