How do I get a single digit from a 4 digit input (the input is in <p> tag) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

How do I get a single digit from a 4 digit input (the input is in <p> tag)

I have created a code that inputs a no. (whichever digit key is pressed)to a <p> tag, it is only 4 digit so now I have to assign each digit to a separate variable, can somebody help me?

21st May 2017, 5:44 PM
_Retr0/-
_Retr0/- - avatar
1 Answer
+ 5
I have some trouble understanding your question but I'll say a few things that hopefully answer you. You can get the digits from an input that is contained within a "p" element using JavaScript like: var s = document.querySelector('p input').value; Regardless of where you get the string, if you want to strip it down to (0-9) digit characters only, you can use a regular expression like this: s = s.replace(/\D/g,''); // Filter out all characters except "0123456789" The above would be useful if you had to get your 4 digits from a string like "Hello 1234 World". Assuming a string is at least 4 characters long, you can access each of the characters like this: var character1 = s.charAt(0); var character2 = s.charAt(1); var character3 = s.charAt(2); var character4 = s.charAt(3); If this wasn't for a lesson but for a more practical project, I would avoid making such similar variables like that. Maybe you haven't studied these yet but Array and the string that you're pulling those characters from are likely better types to use.
14th Jun 2019, 4:04 PM
Josh Greig
Josh Greig - avatar