Last updated: Apr 7, 2024
Reading time·2 min

To use the substring() method in React:
const App = () => { const str = 'Walk the dog'; const result = str.substring(0, 4); console.log(result); // 👉️ "Walk" return ( <div> <h2>{result}</h2> </div> ); }; export default App;

The String.substring() method returns a slice of the string from the start index to the excluding end index.
The method takes the following parameters:
| Name | Description |
|---|---|
| start index | The index of the first character to include in the returned substring |
| end index | The index of the first character to exclude from the returned substring |
If no end index is specified the slice goes to the end of the string.
0 and the last index is str.length - 1.You can also use the substring method directly in your JSX code.
const App = () => { const str = 'Walk the dog'; return ( <div> <h2>{str.substring(0, 4)}</h2> </div> ); }; export default App;
If you only pass a start index to the method, it will return a new string containing the remaining characters.
const App = () => { const str = 'Walk the dog'; const result = str.substring(5); console.log(result); // 👉️ "the dog" return ( <div> <h2>{result}</h2> </div> ); }; export default App;

We started extracting characters at index 5 and went til the end of the
original string.