Ahmad
Ahmad

Reputation: 35

How to extract number from string using javascript?

I am to trying to extract numbers from string for example

East Texas Baptist University (582) (COL)

North Central Texas Academy (202471) (COL)

Bloomfield College (1662) (COL)

I have used parseInt but it gives me NAN. Can any one please suggest a better way. Thanks

Upvotes: 0

Views: 136

Answers (2)

Vladimirs
Vladimirs

Reputation: 8619

You can use regex for that like:

"Bloomfield College (1662) (COL)".match(/(\d+)/)[0] //1662

Upvotes: 4

friedi
friedi

Reputation: 4360

Try this:

function getNumber(str) {
    return parseInt(str.match(/\d+/)[0], 10);
}

You can use the function like this:

var num = getNumber('East Texas Baptist University (582) (COL)');

Upvotes: 3

Related Questions