Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to get the first 4 numbers in a string?

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?

like image 633
like-a-trainee Avatar asked Jun 19 '12 08:06

like-a-trainee


People also ask

How can I extract a number from a string in JavaScript?

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+)/).

How do you get the first 5 characters of a string in typescript?

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 .

How do you get the first digit of a number JavaScript?

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.

Which will return first 3 characters of string?

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.


1 Answers

mystring = "9862 ....... -pack size 1 - SST Unspun Label (Roll) CAT#: 9862";

mystring = mystring.substring(0, 4);

alert(mystring.trim());
like image 53
Someth Victory Avatar answered Oct 27 '22 14:10

Someth Victory