在javascript中,我们可以通过3种方式分割 字符串。一种是使用string.split()方法的旧方法,后来,ES6提供了另外两种拆分字符串的方法。第一种方法使用散布运算符 ,第二种方法使用array.from()方法。让我们详细讨论它们。
string.split();
在下面的示例中,使用string.split() 方法将提供的字符串拆分为每个单独的字符。
<html>
<body>
<script>
const str = 'Nhooo'
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(str);
在以下示例中,ES6 Array.from() 被用于分割 所提供的串入每个和个性。它的工作原理与string.repeat()方法相同。
<html> <body> <script> const str = 'Tutorix and Nhooo' 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