jQuery Extract numbers from string | Lessoncup Programming Blog

Saturday, 7 December 2013

jQuery Extract numbers from string

Hi, today i am going to tell you about a small trick and most useful concept, sometimes when we working with some applications or websites we want use the number inside the string, in that time what you do, it's simple we can do with Regular expression and match() method, recently i got the same situation when i working with twitter app where i used same concept to extract the number form string


HTML

<div  id="string">143users 1male 141females others1</div>

<input name="" type="button" id="button" value="Click Me to Extract">

<div id="result"></div>

JAVASCRIPT

i have just used match() method and added some regular Expression to match with string data and i used for loop to display all extracted numbers into the result div.
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>

<script>

$(document).ready(function(){
 
 $('#button').click(function(){
  
  var string = $('#string').text();
  
  var getNum = string.match(/(\d+)/g);
  
  for(i=0; i<getNum.length; i++){
   
   
   $('#result').append("Array index[" + i + "]:- " + getNum[i]+"<br/>");
   
  }
  
 });
 
})


</script>

Live Demo

3 comments :

  1. thank you very much, hope u have many Tutorial helpful for me

    ReplyDelete
  2. You dont need jQuery but just a line of code:

    var Result = '143users1male'.replace(/[^0-9]/g,'').split('');

    ReplyDelete

Mohammad Khasim
Blogger | Web Developer
Hyderabad - INDIA
lessoncup@gmail.com

PHP | My SQL | JQUERY
Web Development Tools | CMS | Frameworks | SEO

Get my Latest Lessons