Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can get only numbers from the text using jquery

Tags:

I want to get only the numbers(123) not the text(confirm), here is my code

<p>123confirm</p>  <script type="text/javascript"> $(document).ready(function(){     $('p').click(function(){       var sd=$(this).text();       alert(sd);   }); });   </script> 
like image 340
Suresh Pattu Avatar asked Dec 02 '11 13:12

Suresh Pattu


People also ask

How do I allow only numbers in a text box?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.

How do I get just the value of an integer in jQuery?

Answer: Use the jQuery. isNumeric() method You can use the jQuery $. isNumeric() method to check whether a value is numeric or a number. The $. isNumeric() returns true only if the argument is of type number, or if it's of type string and it can be coerced into finite numbers, otherwise it returns false .


2 Answers

I think a RegExp would be a good idea:

var sd = $(this).text().replace(/[^0-9]/gi, ''); // Replace everything that is not a number with nothing var number = parseInt(sd, 10); // Always hand in the correct base since 010 != 10 in js 
like image 150
mfeineis Avatar answered Sep 21 '22 15:09

mfeineis


You can use parseInt for this, it will parse a string and remove any "junk" in it and return an integer.

As James Allardice noticed, the number must be before the string. So if it's the first thing in the text, it will work, else it won't.

-- EDIT -- Use with your example:

<p>123confirm</p>  <script type="text/javascript"> $(document).ready(function(){     $('p').click(function(){       var sd=$(this).text();       sd=parseInt(sd);     alert(sd);   }); });   </script> 
like image 26
jValdron Avatar answered Sep 19 '22 15:09

jValdron