# Solutions For Using The Substring() Method In React

This article will show you solutions for using the substring() method in React. Here are some ways to do it, with examples to make it easier for you to understand.

## Using the substring() method in React

The string. substring() method will extract the content of a string. The extracted content will be determined by two parameters, start, and end. The method will return the content extracted from the original string.

Syntax:

string.substring(start, end)

Parameters:

• start is the starting position to extract.
• end is the end position. Extraction will not include the end element.

This way, we will pass all the necessary parameters of the method, which are start and end, and the program will know where the string we need to get from is, as in the example below.

Code:

import React, { useState } from "react";

export default function App() {
var string = "LearnShareIT";
const [subString, setSubString] = useState(string);
return (
<div className="App">
<h2>Using the substring() method in React | LearnShareIT</h2>
<h3>{subString}</h3>
<button
onClick={() => {
setSubString(string.substring(5, 10));
}}
>
Substring
</button>
</div>
);
}

Output:

Here, from the original string “LearnShareIT”, we use the substring() method and pass it on to two parameters, 5 and 10. The method will receive 5 as the starting value of the cut and 10 as the end value. So we can get the string “Share” from the original string “LearnShareIT”. Even if we change the code to:

string.substring(10, 5)

Javascript will still notice that the start value is greater than the end value, so that it will reverse and still give the same result.

### Only add the start parameter

So what if you pass in a single parameter? The program will default to select it as the start parameter and how to return the results. See the example below to understand more.

Code:

import React, { useState } from "react";

export default function App() {
var string = "Leonardo DiCaprio";
const [subString, setSubString] = useState(string);
return (
<div className="App">
<h2>Using the substring() method in React | LearnShareIT</h2>
<h3>{subString}</h3>
<button
onClick={() => {
setSubString(string.substring(8));
}}
>
Substring
</button>
</div>
);
}

Output:

So as you can see in the above example, when we only pass the start parameter, the default end parameter is setting to the last index value of the string. For example, the string “Leonardo DiCaprio” becomes the string “DiCaprio”. Hope you have success with the above methods.

## Summary

To summarize, through this article, you have learned some ways for using the substring() method in React, such as adding full parameters method or only adding the start parameter. Have a good day.

Maybe you are interested: