Suresh Pattu
Suresh Pattu

Reputation: 6209

how can get only numbers from the text using jquery

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>

Upvotes: 27

Views: 74560

Answers (5)

Pradeep Kumar
Pradeep Kumar

Reputation: 21

Regex works for me also

var trdata = $(this).text().replace(/[^0-9]/gi, '');
console.log(parseInt(trdata, 10));

Upvotes: 1

Sani Kamal
Sani Kamal

Reputation: 1238

You can also use this method:

 $('#totalseat').change(function() {
    var totalseat=$('#totalseat').val();
    var price=$('#seat_type option:selected').text().replace(/[^0-9]/gi,'');
    // Always hand in the correct base since 010 != 10 in js
    var price_int = parseInt(price,10);
    var total_price=parseInt(totalseat)*price_int;
    $('#totalprice').val(total_price);

});

Upvotes: 1

jValdron
jValdron

Reputation: 3418

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>

Upvotes: 28

Sal
Sal

Reputation: 1655

You can also use this method:

$(document).ready(function(){  
  $(p).click(function(){  
    var sd=$(this).text();
    var num = sd.match(/[\d\.]+/g);
    if (num != null){
        var number = num.toString();
        alert(number );
    }
  });
});  

Upvotes: 6

mfeineis
mfeineis

Reputation: 2657

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

Upvotes: 51

Related Questions