Using the substring() method in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Using the substring() method in React

To use the substring() method in React:

  1. Call the method on a string.
  2. Supply the start and end indexes as parameters.
  3. The method returns a new string containing only the specified part of the original string.
App.js
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;

using substring method in react

The code for this article is available on GitHub

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:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe 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.

JavaScript indexes are zero-based, so the first index in a string is 0 and the last index is str.length - 1.

You can also use the substring method directly in your JSX code.

App.js
const App = () => { const str = 'Walk the dog'; return ( <div> <h2>{str.substring(0, 4)}</h2> </div> ); }; export default App;
The code for this article is available on GitHub

If you only pass a start index to the method, it will return a new string containing the remaining characters.

App.js
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;

only passing start index to substring method

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.