Domanda

Hello everyone,

I'm trying to find the best way to cut out specific parts of the below input string. I'm using a white space (' ') as a separator. But I'm unable to cut out the required parts and assign them into respective variables.

var input = "/w user1 message"

var user = input.substring(2, input.indexOf(' '));?? 
var message = ???

expected result:

user = "user1"
message = "message"

It only works when the empty spaces are replaced with a coma or any other separator.

Is there any specific reason why iit's not working with spaces?

Thanks in advance, Alex

È stato utile?

Soluzione

I would recommend using split, it creates an array and you can just access the array by index

http://jsfiddle.net/PJH28/

var input = "/w user1 message"

var inputParts = input.split(' ');
var message = inputParts[2];
console.log(message);

Altri suggerimenti

Just try with:

var message = input.substr(input.indexOf(' ', input.indexOf(' ') + 1) + 1);

You could do something like this..

// set up
var commands = {
    '/w': ['user']
};

//later
var arr = input.split(' '), o = {}, i;
if (arr[0] in commands) {
    o.command = arr.shift();
    for (i = 0; i < commands[o.command].length; ++i) {
        o[commands[o.command][i]] = arr.shift();
    }
}
o.message = arr.join(' ');
o;

Testing with your var input = "/w user1 foo bar baz"; gives me

Object {command: "/w", user: "user1", message: "foo bar baz"}

This should now be much easier to use with other things

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top