在 JavaScript 中,我们可以通过多少种方式拆分字符串?
javascriptobject oriented programmingfront end technology更新于 2025/5/31 17:16:17
在 JavaScript 中,我们可以通过 3 种方式拆分 字符串。一种是使用 string.split() 方法的旧方法,后来,ES6 提供了另外 2 种拆分字符串的方法。第一种方式使用 split 运算符 ,第二种方式使用 array.from() 方法。让我们详细讨论一下它们。
String.split()
语法
string.split();
示例
在下面的示例中,使用 string.split() 方法将提供的字符串拆分为每个单独的字符。
<html>
<body>
<script>
const str = 'Tutorialspoint'
var d = str.split('')
document.write(d);
</script>
</body>
</html>
输出
T,u,t,o,r,i,a,l,s,p,o,i,n,t
扩展运算符
语法
[...string];
示例
在下面的示例中, ES6 扩展运算符用于将提供的字符串拆分成每个单独的字符。与 string.split()方法相比,它的用法非常简单。
<html> <body> <script> const str = 'Tutorix' var d = [...str] document.write(d); </script> </body> </html>
输出
T,u,t,o,r,i,x
Array.from()
语法
Array.from(str);
示例
在以下示例中,ES6 Array.from() 用于将提供的字符串拆分为各个字符。其工作原理与 string.repeat() 方法相同。
<html> <body> <script> const str = 'Tutorix and Tutorialspoint' var d = Array.from(str); document.write(d); </script> </body> </html>
输出
T,u,t,o,r,i,x, ,a,n,d, ,T,u,t,o,r,i,a,l,s,p,o,i,n,t
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

