在 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 处开始提取字符,一直到原始字符串的末尾。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。