我有一個簡單的問題,我認為我需要幫助。所以,我有一個接受這種格式的字串的函式
"1. Crowe, Velvet (LoC), 2. Hume, Eleanor (Ext), 4. Shigure, Rokurou (DmN), 10. Mayvin, Magilou (MgC)"不帶引號。
基本上,一個帶有等級編號的人名串列。
我想要的是拆分它們以便我得到 ff 結果:
[
"1. Crowe, Velvet (LoC)",
"2. Hume, Eleanor (Ext)",
"4. Shigure, Rokurou (DmN)",
"10. Mayvin, Magilou (MgC)"
]
有沒有辦法做到這一點?我使用split()了方法,但每次看到出現逗號時都會拆分字串。
uj5u.com熱心網友回復:
您可以使用正則運算式進行拆分/(?<=\)),\s/:
const str = "1. Crowe, Velvet (LoC), 2. Hume, Eleanor (Ext), 4. Shigure, Rokurou (DmN), 10. Mayvin, Magilou (MgC)";
const res = str.split(/(?<=\)),\s/);
console.log(res);
這將按照cmgchess在評論中的), 建議進行拆分。基于字串進行拆分的問題在于它會洗掉一些您想要保留的字符。相反,通過使用正則運算式,您可以使用(這里稱為肯定的lookbehind)來匹配并保留在結果拆分元素中。然后根據逗號后跟空格 ( ) 進行拆分。(?<=\))?<=),\s\s
您還可以使用以下正則運算式,.match()它更健壯一些,但可能需要根據您的數字/排名之后的文本進行更新:
/\d \.\s\w ,\s\w \s\(\w \)/g
以上執行:
\d \.: 將匹配一個或多個 () 數字后跟一個點\s: 匹配一個空白字符\w ,: 匹配多個 () 單詞字符 (\w) 中的一個,后跟逗號,\s: 匹配一個空格\(\w \): 匹配括號內的單詞字符()/g:用于匹配字串中所有出現的序列的全域標志
const str = "1. Crowe, Velvet (LoC), 2. Hume, Eleanor (Ext), 4. Shigure, Rokurou (DmN), 10. Mayvin, Magilou (MgC)";
const res = str.match(/\d \.\s\w ,\s\w \s\(\w \)/g);
console.log(res);
uj5u.com熱心網友回復:
@cmgchess只是對答案的一點改進(添加trim洗掉不必要空格的方法):
const getUsers = (str) => {
const users = str.split('),').map(x => x.trim() ')');
users[users.length - 1] = users[users.length - 1].replace('))', ')');
return users;
}
console.log(getUsers("1. Crowe, Velvet (LoC), 2. Hume, Eleanor (Ext), 4. Shigure, Rokurou (DmN), 10. Mayvin, Magilou (MgC)"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/440201.html
標籤:javascript 数组 细绳 分裂
