我想拆分包含 ""
和空格的字符串。
我的输入是:
'!command "string one" so "string two" st "string three" st'
数组应该是:
array[0] = "string one"
array[1] = "so"
array[2] = "string two"
array[3] = "st" // ect....
现在这是我的代码,它接受命令及其背后的参数:
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
最佳答案
使用正则表达式和 .match
非 "
字符,或匹配非空格(第一个字符不是 "
):
const input = '"string one" so "string two" st "string three" st';
const output = input.match(/\b[^"]+\b|(?!")\S+/g);
console.log(output);
或者,为了更稳健一点,也匹配 "
,然后匹配 .map
:
const input = '"string one" so "string two" st "string three" st';
const output = input
.match(/"[^"]+"|\S+/g)
.map(str => str.startsWith('"') ? str.slice(1, str.length - 1) : str);
console.log(output);
关于javascript - 使用Javascript将字符串以多种方式拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003939/