[英]How to split a javascript string on spaces and non alphanumeric characters while keeping spaces
[英]How to split string into characters but to keep spaces in javascript
我想將字符串拆分為字母,並在前一個字母中保留空格。 例如,我有這個字符串“ Lo ip som”。 我想得到這個結果['L','o','i','p','s','o','m','。']。 '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;
}
你可以這樣
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.