0

So as said in last question i was making some console shet for my other stuff and got into some problems

i wanted to get string from input to variable to split it but it does not get anything, it's clear :\

this was my variable code

var args = consoleInput.value.split(/(\s+)/)

and then i wanted to see it using console log like this

console.log(args)

but output is this

>[""]

And nothing else

JS:


const consoleInput = document.getElementById("input");

var args = consoleInput.value.split(/(\s+)/)
console.log(args)

HTML:

<div class="inputTextDiv">
   <span id="inputText"></span><br>
</div>
<input type="text" placeholder="Insert Command ;P" id="input">
10
  • You have to reference inputText.value to get the contents of the text box. Commented Jul 15, 2021 at 18:40
  • var args = inputText.value.split(/(\s+)/) Uncaught TypeError: Cannot read property 'split' of undefined at main.js:26 Commented Jul 15, 2021 at 18:43
  • That could mean that inputText is null, meaning that there's no element in the DOM with that id. Commented Jul 15, 2021 at 18:44
  • ... at the time of execution Commented Jul 15, 2021 at 18:46
  • It's not at all clear what you're asking. Can you please remove any code that isn't relevant to your question (does the useConsole stuff have anything to do with anything?), include the relevant HTML, and be clearer about what the problem you're having is? Commented Jul 15, 2021 at 18:46

1 Answer 1

1

I suspect the reason you were seeing an empty array is because you were running your code while the input field was empty.

Here I've attached it to fire whenever the input field receives input:

document.querySelector('input').oninput = () => {
  const consoleInput = document.getElementById("input");
  var args = consoleInput.value.split(/(\s+)/)
  console.log(args)
}
<div class="inputTextDiv">
   <span id="inputText"></span><br>
</div>
<input type="text" placeholder="Insert Command ;P" id="input">

(I also suspect that your regex ought to be /\s+/ instead of /(\s+)/, unless you really want to be capturing the spaces as part of the array.)

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

2 Comments

You can split empty strings without errors
Yep, but the capture group in the regex includes the spaces in the array instead of just splitting on them, which I'm guessing wasn't intended.

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.