Using the substring() method in React

avatar

Borislav Hadzhiev

Last updated: May 2, 2022

banner

Photo from Unsplash

Using the substring() method in React #

To use the substring() method in React:

  1. Call the method on a string.
  2. Pass it 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;

The two parameters we passed to the String.substring method are:

  1. the start index - the index of the first character to be included in the returned string
  2. the end index - go up to, but not including this index
Indexes are zero-based in JavaScript, which means that the first index in a string is 0 and the last 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;

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;

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.