0

Im trying to split a user input value by the first space.

Example: User inputs the following command: /command test command into a input field.

The code now removes the first charackter in that string which would be: /

Now the code should split the remaining input ("command test command") by the first whitespace, so the following would remain:

  • command
  • test command

My problem is the following: My code splits the command at any whitespace. A example is made here:

$("#execute").click(function() {
  var command = $("#command").val().substr(1);
  var args = command.split(/[ ]+/);
  var commandName = args[0];
  args.shift()
  
 $("#content").text("Command: " + commandName + " Text: " + args);
});
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8">
    <title>Berechnen votes</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

  <body>
    <input id="command" type="text" value="/command test command">
    <button id="execute">Execute</button>
    <br><br>
    <span id="content"></span>
  </body>

</html>

I appreciate any kind of help!

pr0b
  • 377
  • 2
  • 3
  • 14
  • We can't point the bug in your code if you don't share it. – Denys Séguret Jun 29 '18 at 13:08
  • Edited the question, didnt work out as i expected it before. – pr0b Jun 29 '18 at 13:10
  • After extracting the word `command` from the array, the remaining items in the array is the rest, so just join them together again? You could use a more complicated splitting regex, but for trivial things like this, that seems overkill. – Shilly Jun 29 '18 at 13:11
  • `.indexOf(' ')` will give you the position of the first space, `.substr()` will let you read before/after that point. – Alex K. Jun 29 '18 at 13:11
  • Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Leo K Jun 29 '18 at 14:16

1 Answers1

0

You should use a regular expression:

let input = " /command test command";
let [, command, args] = input.match(/^\W*(\S+)\s+(.*)$/);

console.log("command:", command);
console.log("args:", args);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758