Thursday 3 April 2014

Get Numbers from String in Javascript 0

In this post, We are going to learn how to get only numbers from string using Javascript. To do this we are going to use one of the power full weapon Regular Expression.

In this bellow example we are getting value from text box and get only numbers using javascript's .replace().replace() method.

Here we are going to use non-digit character equivalent ( \D ). Just find the non-digit character and replace with " " empty.

var $ = function (id) {
    return document.getElementById(id);
};
$('btn').addEventListener('click', function () {
    $('num').innerHTML = $('abc').value.replace(/\D/g, '');
});

NOTE : Here I used $ as a shorthand for document.getElementById(). To know more about shorthand, you can refer one of my previous post Shorthand for getElementById in Javascript.

Or you can simply use like this below, 

document.getElementById('btn').addEventListener('click', function() {
    document.getElementById('num').innerHTML = document.getElementById('abc').value.replace(/\D/g, '');
});

after click on the "Click me !!!" button, it will alert the number you used in text box.

0 comments:

Post a Comment