如何在 React 中使用 substring() 方法
投稿:mrr
这篇文章主要介绍了在 React 中使用 substring() 方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
在 React 中使用 substring() 方法:
- 在字符串上调用该方法。
 - 将开始和结束索引作为参数传递给它。
 - 该方法返回一个仅包含原始字符串指定部分的新字符串。
 
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;我们传递给 String.substring 方法的两个参数是:
- start 索引 – 要包含在返回字符串中的第一个字符的索引
 - end 索引 – 截止到end,但不包括这个索引
 
JavaScript中的索引是从零开始的,这意味着字符串中的第一个索引是 0,最后一个索引是str.length - 1。
我们也可以直接在 JSX 代码中使用 substring 方法。
const App = () => {
  const str = 'Walk the dog';
  return (
    <div>
      <h2>{str.substring(0, 4)}</h2>
    </div>
  );
};
export default App;如果我们只将起始索引传递给该方法,它将返回一个包含剩余字符的新字符串。
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;我们从索引 5 处开始提取字符,一直到原始字符串的末尾。
到此这篇关于在 React 中使用 substring() 方法的文章就介绍到这了,更多相关React使用 substring() 方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
