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

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

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

mystring = mystring.substring(0, 4);

alert(mystring.trim());

You can do either:

mystring=mystring.substring(from,to);

or

mystring=mystring.substr(start,length);

If the start is 0 (like your case), the two ways will be the same.

Sources:

http://www.w3schools.com/jsref/jsref_substr.asp
http://www.w3schools.com/jsref/jsref_substring.asp

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

var extractInts = function(str) {
    r = [];
    for ( var i = 1, l = str.length; i <= l; ++i ) {
        if ( !isNaN(parseInt(str.substring(i-1, i),0))) {
            str = str.substring(i-1);
            r.push(parseInt(str, 0));
            str = str.substring( parseInt(str,0).toString().length);
            i = 1;
        }
    }
    return r;
};

var str = Hi, here is an int 1, and another 3, and finally 37;
var i_array = extractInts(str);
console.log(extractInts:  + i_array[0]); //Prints 1

The above function will extract every integer into an array, and hence you can just extract the first.

Leave a Reply

Your email address will not be published.