如何用逗号分割参数数组?

时间:2019-03-30 05:51:13

标签: node.js

这是针对基于NodeJS的Discord Bot。基本上我想做的是获取用户参数,但我希望用户输入的参数以逗号分隔。因此,例如,如果用户执行了此命令!check this is arg1, this is arg2

我尝试了以下操作:

const args = message.content.slice(prefix.length).split(',');

但是,当我这样做时,它根本什么也不做,就像我调用命令一样,它什么也不会做,但是如果我这样做:

const args = message.content.slice(prefix.length).split(' ');

该命令将按原样进行响应,但是现在它会将参数拆分为空格而不是逗号。

这是我的代码:

client.on('message', message => {
    const args = message.content.slice(prefix.length).split(',');
    const command = args.shift().toLowerCase();

    if(command == "check"){
        console.log(args);
        if(args == "") return message.channel.send("You didn't specify any symptoms.");

        let s1 = args[0];
        let s2 = args[1];
        if(typeof s2 != "undefined"){
            return message.channel.send(`Args: ${s1}, ${s2}`);    
        } else {
            return message.channel.send(`Args: ${s1}`);    
        }

    }
});

2 个答案:

答案 0 :(得分:1)

我的一般建议是做这样的事情:

// suppose
var message = "!check this is arg1, this is arg2"

// use regex to separate command (and grab it) from args
var input = message.match(/^!(\b\w+\b) (.*)/i)

// output: Array(3) [ "!check this is arg1, this is arg2", "check", "this is arg1, this is arg2" ]
// then input[1] is your command, input[2] are the args

// split without regex is usually faster
var args = input[1].split(', ').map(arg => arg.trim())
// output is Array [ "this is arg1", "this is arg2" ]

您可以转到here翻译regex

答案 1 :(得分:0)

您可以使用.split(',')

示例

const text = 'this is arg1, this is arg2' // text to split

const textarr = text.split(', ');
for(var i = 0; i < textarr.length; i++){
   console.log(textarr[i] + '\n')
}