[英]JS / TS splitting string by a delimiter without removing the delimiter
我有一個字符串,我需要通過某個分隔符拆分並轉換為數組,但不刪除分隔符本身。 例如,請考慮以下代碼:
var str = "#mavic#phantom#spark";
str.split("#") //["", "mavic", "phantom", "spark"]
我需要輸出如下:
["#mavic", "#phantom", "#spark"]
我在這里讀到但這並沒有回答我的問題。
你可以通過#
的積極前瞻來split
。
var string = "#mavic#phantom#spark", splitted = string.split(/(?=#)/); console.log(splitted);
用#
拆分字符串並使用reduce
返回修改后的字符串
var str = "#mavic#phantom#spark"; let x = str.split("#").reduce((acc, curr) => { if (curr !== '') { acc.push('#' + curr); } return acc; }, []) console.log(x)
這里還有一些解決你的任務的非正則表達方法:
解決方案1經典方法 - 遍歷字符串,每次當我們找到indexOf
我們的分隔符時,我們將結果數組推送到當前位置和下一個位置之間的子串。 在else塊中,我們有一個最后一個子字符串的大小寫 - 我們只需將它添加到結果數組中並打破循環。
const delimiter = '#';
const result1 = [];
let i = 0;
while (i < str.length) {
const nextPosition = str.indexOf(delimiter, i+1);
if (nextPosition > 0) {
result1.push(str.substring(i, nextPosition));
i = nextPosition;
} else {
result1.push(str.substring(i));
break;
}
}
解決方案2 - 從索引1開始拆分初始字符串(為了在結果數組中不包含空字符串),然后通過連接分隔符和當前數組項來映射結果數組。
const result2 = str.substr(1).split(delimiter).map(s => delimiter + s);
另一種方法:在拆分后過濾空元素,並將這些元素映射為以您分割的字符開頭。
string.split("#").filter((elem) => elem).map((elem) => "#" + elem);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.