Get numbers from strings in Javascript

javascript

Here’s a small javascript utility function to get numbers from strings.

String.prototype.getNum = function() {
	thisNum = '';
	for (var i = 0; i<this.length; i++) {
		myChar = this.charAt(i);
		if (!isNaN(myChar)) {
			thisNum += myChar;
		}
	}
	return thisNum;
};

This is how you use it.

var myString = "this is number 67890";
console.log(myString.getNum());  //returns 67890

Hope this helps! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>