1

I'm rewriting one of my scripts right now and encountered a problem I just can't figure out. command is an input variable and now I've run this test (both regular expressions are the same):

var parts = command.match(/([^\s"]+(?=\s*|$))|(".+?")/g);
console.log(command === "view -10 10 -10 10");
console.log(parts);
console.log(String("view -10 10 -10 10").match(/([^\s"]+(?=\s*|$))|(".+?")/g));

The console now says

true
[]
["view", "-10", "10", "-10", "10"]

This completely confuses me. Why does command not get separated the same way, when it equals my test string even when using ===?

16
  • 2
    I tried your example in Chrome, and it works as expected. Which Browser are you using? Commented Sep 16, 2012 at 10:48
  • You might want to look into whether command is being populated as-expected. Is it async? Is it server-side or user-facing? Commented Sep 16, 2012 at 10:50
  • Perhaps it is a scope issue??? Commented Sep 16, 2012 at 10:52
  • 4
    I suggest you explain it in an answer and then accept your answer. This might help somebody's else later. Commented Sep 16, 2012 at 11:14
  • 1
    @Ingo dystroy added the solution for you, it would be nice if you could mark it as "accepted". Commented Sep 17, 2012 at 14:28

1 Answer 1

1

From OP

Here's the solution to the whole problem: The basic structure of the program was as follows

while (<condition>) {
    var command = getNextCommand();

    var parts = command.match(/([^\s"]+(?=\s*|$))|(".+?")/g);
    processParts(parts);
}

wherein processParts() manipulated the argument:

function processParts(parts) {
    var foo = parts.shift();
    doSomethingElse(foo);
}

This caused parts in the main routine to shrink and in my code processParts actually shifted all elements, causing console.log(parts) to write an empty array as it was logged delayed (see dystroy's comment).

On top of that, my processParts() function had a mistake which I didn't notice and which is what I blamed the empty parts for. After fixing that mistake the above code worked again as I didn't need parts anymore and could live with it having shrunk. In general you might wanna watch out for that, though ... JavaScript does some weird stuff.

Sign up to request clarification or add additional context in comments.

Comments

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.