Js 中截取字符串的方法
在 JavaScript 中,有多种方法可以截取字符串的子串。
1. 使用 slice() 方法
slice() 方法是最常用的截取字符串的方法。它接受两个参数:
- start:开始截取的索引(包括)
- end:结束截取的索引(不包括)
<code class="js">const str = "Hello World"; const result = str.slice(0, 5); // "Hello" console.log(result);</code>
2. 使用 substring() 方法
substring() 方法与 slice() 方法类似,但它不接受负索引。
<code class="js">const str = "Hello World"; const result = str.substring(0, 5); // "Hello" console.log(result);</code>
3. 使用 substr() 方法
substr() 方法是一个较旧的方法,与 slice() 方法类似,但它接受第一个参数作为开始截取的索引,第二个参数作为截取的长度。
<code class="js">const str = "Hello World"; const result = str.substr(0, 5); // "Hello" console.log(result);</code>
4. 使用正则表达式
可以使用正则表达式来截取字符串。
<code class="js">const str = "Hello World"; const result = str.match(/Hello/g); // ["Hello"] console.log(result);</code>
根据你的需要选择最适合的方法。slice() 方法是最常用和最灵活的方法。