在学习Vue( ) 的过程中,用到了JavaScript的split( )方法
split( )方法能够把一个字符串分割为字符串数组,下面通过实例演示一下
我这里设定字符串是Hello the world of JavaScript!
HTML代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS学习</title>
</head>
<body>
<script type="text/javascript">
var str = "Hello the world of JavaScript!";
// 把一个字符串分割成字符串数组
document.write(str.split(" ") + "<br/>");
document.write(str.split("") + "<br/>");
document.write(str.split(" ",4))
</script>
</body>
</html>
运行结果:
HTML中我写了3种分割字符串的方法
1、
document.write(str.split(" ") + "<br/>");
split中为空格符,字符串由逗号分割为一个个单词,注意它无法把标点符号单独分割
Hello,the,world,of,JavaScript!
2、
document.write(str.split("") + "<br/>");
无空格符,把字符串分割为一个个字母和空格
H,e,l,l,o, ,t,h,e, ,w,o,r,l,d, ,o,f, ,J,a,v,a,S,c,r,i,p,t,!
3、
document.write(str.split(" ",4))
这里split( )包含了可选项
该参数可指定返回的数组的最大长度,这里我选定了4,就是前4个单词
Hello,the,world,of
此外,它还可以根据字符串中的标点进行分割
例如:
var str2 = "hello1:2:3:4:5";
由冒号:进行分隔
document.write(str2.split(":") + "<br/>");
结果:
hello1,2,3,4,5