mystring = "9862 ....... -pack size 1 - SST Unspun Label (Roll) CAT#: 9862"
I want to get the first 4 numbers in this string "9862". How do I get the first sequence of numbers in this string. And store it in anothoer variable?
Javascript doesn't seem to be recognizing this variable. I don't know why. if I do:
alert(mystring); //I don't get an alert pop up nor does it show any errors.
Could there something be wrong with the text I'm trying to store in 'mystring' variable?
The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).
To get the first N characters of a string, we can also call the substring() method on the string, passing 0 and N as the first and second arguments respectively. For example, str. substring(0, 3) returns a new string containing the first 3 characters of str .
To get the first digit of a number:Access the string at index 0 , using square brackets notation e.g. String(num)[0] . Convert the result back to a number to get the first digit of the number.
Use the string. slice() method to get the first three characters of a string, e.g. const first3 = str. slice(0, 3); . The slice method will return a new string containing the first three characters of the original string.
mystring = "9862 ....... -pack size 1 - SST Unspun Label (Roll) CAT#: 9862";
mystring = mystring.substring(0, 4);
alert(mystring.trim());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With