2

I am making a warn command of an bot (Discord Api) I learnt how to split a string . So , The example is

var str = "warn @user reason";
var res = str.split(" ", 3);

and Its output will be

warn,@user,reason

and Its output will be "warn,@user,reason" I want to make the reply come in variables like

var commandname = "warn" ;
var username = "@user"; 
var reason = "reason"; 

because I want to store them in a file ! How can I remove the "," of reply and get the reply as the variables ?

3
  • 1
    You can set as commandname = res[0]; username = res[1]; ... Commented Sep 25, 2017 at 10:50
  • 3
    You already has the values in a variable called res, which is even easier to save into a file than separate variables. Commented Sep 25, 2017 at 10:53
  • 5
    Possible duplicate of Javascript separate string into different variables Commented Sep 25, 2017 at 10:54

2 Answers 2

5

In your example, res will be an array of string objects. So you can access then by index:

var commandname = res[0];
var username = res[1]; 
var reason = res[2]; 
Sign up to request clarification or add additional context in comments.

3 Comments

Should we really answer such basic questions?
Yep. As long as the question meets all the requirements (effort, clear, etc.) then it doesn't matter how 'simple' you or anyone else thinks it is. Only thing I didn't think of, maybe it's a duplicate already...
I agree with musefan, simple is relative
3

You can simplify var declaration like , for further details about Destructuring assignment

var str = "warn @user reason";
var res = str.split(" ", 3);
var [commandname,username,reason ] = res;
console.log(commandname);
console.log(username);
console.log(reason);

Note: It depends upon ES version and do not support by IE

5 Comments

Depends on the ES version
Never knew that, it's good to learn... though I doubt I would use it anytime soon. Doesn't seem like much of a time saver for the risk of compatibility
Unless specified, it's about time we put ES5 were it belongs, (in the bin).. If the OP specifically asks for ES5, fair enough. But come on..!! As a default javascript questions ES6 should be the norm..
@musefan It's called destructuring
yes, added link for Destructuring assignment in answer and note as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.