拆分不以当前格式显示

时间:2019-02-09 18:16:45

标签: javascript

我有这个字符串:

var mystring = "save 'myfile.txt' 'this is the content'";

我需要这样打破它:

var command = mystring[0];
var filename = mystring[1];
var content = mystring[2];

我正在使用这个:

var mystring = message.content.split("'' ,");

这什么也没显示

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以匹配零件并使用destructuring assignment

var string = "save 'myfile.txt' 'this is the content'",
    [, command, filename, content] = string.match(/(.*) '(.*)' '(.*)'/);
    
console.log(command);
console.log(filename);
console.log(content);

答案 1 :(得分:2)

您可以使用正则表达式进行拆分:mystring.split(/'?\s*'/)

var mystring = "save 'myfile.txt' 'this is the content'";
var [command, filename, content] = mystring.split(/'?\s*'/);
console.log({command, filename, content});

答案 2 :(得分:0)

尝试:

const mystring = message.content.split(" ");
const command = mystring[0];
const filename = mystring[1].substr(1,mystring[1].length - 2);
const content = mystring[2].substr(1,mystring[2].length - 2);