[英]split word from string including space using js
我正在嘗試拆分包括字符串在內的字符串,但空間也隨地吐痰。
我的代碼:
var a =' that i love
game1 ';
console.log(a.split(' '))
我當前的輸出是:
(57) ["↵", "", "", "", "", "", "", "", "", "that", "i", "love↵", "", "", "", "", "", "", "", "", "game1↵↵↵", "", "", "", ""]
我試圖得到這樣的輸出:-
(4)[" that",'i',' love',' ↵game'];
如何以包括空格和換行符的方式拆分字符串?
您可以將String#match與正則表達式( regex101 )結合使用以獲取與所需內容相似的內容:
var a =` that i love game1 `; console.log(a.match(/\\s*\\S*/g)); // or console.log(a.match(/\\s*\\S*\\s*/g));
您可以在split
使用正則表達式。
var a =` that i love game1 `; console.log(a.split(/(\\s+\\S+\\s+)/));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.