SoFunction
Updated on 2025-04-07

How to use the substring method in React

Use in Reactsubstring()method:

  • Call this method on a string.
  • Pass the start and end index as parameters to it.
  • This method returns a new string that contains only the specified part of the original string.
const App = () => {
  const str = 'Walk the dog';
  const result = (0, 4);
  (result); // ?️ "Walk"
  return (
    <div>
      <h2>{result}</h2>
    </div>
  );
};
export default App;

We pass it toThe two parameters of the method are:

  • startIndex – The index of the first character to be included in the return string
  • endIndex – ends to end, but does not include this index

JavaScriptThe index in  starts from zero, which means that the first index in the string is0, the last index is - 1

We can also use it directly in JSX codesubstringmethod.

const App = () => {
  const str = 'Walk the dog';
  return (
    <div>
      <h2>{(0, 4)}</h2>
    </div>
  );
};
export default App;

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

const App = () => {
  const str = 'Walk the dog';
  const result = (5);
  (result); // ?️ "the dog"
  return (
    <div>
      <h2>{result}</h2>
    </div>
  );
};
export default App;

We index5The characters are extracted at the beginning, until the end of the original string.

This is the end of this article about using the substring() method in React. For more related contents of using the substring() method in React, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!