JavaScript 字符串分割截取方法详解:split(), slice(), substring(), substr()
JavaScript 字符串分割截取方法详解:split(), slice(), substring(), substr()
JavaScript 中提供了多种方法用于分割和截取字符串,本文将详细介绍其中常用的四种方法,并通过示例代码演示它们的用法。
1. split():将字符串按照指定的分隔符进行分割,返回一个数组。
**示例:**将字符串 'hello world' 按照空格分割成数组。
let str = 'hello world';
let arr = str.split(' ');
console.log(arr); // ['hello', 'world']
2. slice():从字符串中截取指定位置的子串,返回一个新的字符串。
**示例:**将字符串 'hello world' 截取出 'world'。
let str = 'hello world';
let newStr = str.slice(6);
console.log(newStr); // 'world'
3. substring():从字符串中截取指定位置的子串,返回一个新的字符串。
**示例:**将字符串 'hello world' 截取出 'world'。
let str = 'hello world';
let newStr = str.substring(6);
console.log(newStr); // 'world'
4. substr():从字符串中截取指定长度的子串,返回一个新的字符串。
**示例:**将字符串 'hello world' 截取出 'world'。
let str = 'hello world';
let newStr = str.substr(6, 5);
console.log(newStr); // 'world'
总结
本文介绍了 JavaScript 中常用的字符串分割截取方法,希望对您有所帮助。在实际应用中,您可以根据具体的需求选择合适的方法来处理字符串。
原文地址: https://www.cveoy.top/t/topic/ozOW 著作权归作者所有。请勿转载和采集!