js 里的split函数,切割以空格(多个空格)作为分隔符的字符串

在使用split函数切割一个以空格为分隔符的字符串时,发现切出的长度和预期的长度不一致!!

  1. let str = "hellow  world!"            <strong><span style="color:#ff6666;">//注意hellow与world之前有两个空格</span></strong>  
  2. console.log(str.trim().split(" "))  
  3. console.log(str.trim().split(" ").length)  

结果为【“hellow”,“ ”,“world!" 】

 

而我们希望的结果是hellow和world,长度为2

此时,应该用正则表达式来进行切割

  1. let str = "hellow  world!"           <strong><span style="color:#ff6666;"> //注意hellow与world之前有两个空格</span></strong>  
  2. console.log(str.trim().split(/\s+/))  
  3. console.log(str.trim().split(/\s+/).length) 

结果为【“hellow”,“world!" 】

解决问题!希望大家也能注意到这个小坑!  切割前最好先用trim()将首尾的空格去掉

posted on 2018-05-11 12:27  EastChilde  阅读(11277)  评论(0编辑  收藏  举报

导航