[英]How to split string into characters but to keep spaces in javascript
I want to split the string into letters and keep space in previous letter. 我想将字符串拆分为字母,并在前一个字母中保留空格。 For example I have this string "Lo ip som."
例如,我有这个字符串“ Lo ip som”。 and I want to get this result ['L', 'o ', 'i', 'p ', 's', 'o', 'm', '.'].
我想得到这个结果['L','o','i','p','s','o','m','。']。 The 'o ' have space and the 'p ' has space.
'o'有空间,'p'有空间。
"Lo ip som.".trim().split('').map(function (ch, i, array) { return ch == ' ' ? array[i - 1] + ' ' : ch })
function splitString(str){
str = str.trim();
var length = str.length;
retArr = [];
for(var i = 0; i < length; i++){
if(str[i] === ' '){
retArr[retArr.length - 1] += ' ';
continue;
}
retArr.push(str[i]);
}
return retArr;
}
You can do like this 你可以这样
var str = "Lo ip som.", arr = Array.prototype.reduce.call(str,(p,c) => c == " " ? (p[p.length-1]+=" ",p) : p.concat(c),[]); document.write("<pre>" + JSON.stringify(arr) + "</pre>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.