I have a string in JavaScript like #box2
and I just want the 2
from it.
I tried:
var thestring = $(this).attr(\'href\');
var
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g,'');
return parseInt(numsStr);
}
remember: if the number has a zero in front of it, the int wont have it
If someone need to preserve dots in extracted numbers:
var some = '65,87 EUR';
var number = some.replace(",",".").replace(/[^0-9&.]/g,'');
console.log(number); // returns 65.87
You can use Underscore String Library as following
var common="#box"
var href="#box1"
_(href).strRight(common)
result will be : 1
See :https://github.com/epeli/underscore.string
DEMO:
http://jsfiddle.net/abdennour/Vyqtt/
HTML Code :
<p>
<a href="#box1" >img1</a>
<a href="#box2" >img2</a>
<a href="#box3" >img3</a>
<a href="#box4" >img4</a>
</p>
<div style="font-size:30px"></div>
JS Code :
var comm="#box"
$('a').click(function(){
$('div').html(_($(this).attr('href')).strRight(comm))})
if you have suffix as following :
href="box1az"
You can use the next demo :
http://jsfiddle.net/abdennour/Vyqtt/1/
function retrieveNumber(all,prefix,suffix){
var left=_(all).strRight(prefix);
return _(left).strLeft(suffix);
}
var elValue = "-12,erer3 4,-990.234sdsd";
var isNegetive = false;
if(elValue.indexOf("-")==0) isNegetive=true;
elValue = elValue.replace( /[^\d\.]*/g, '');
elValue = isNaN(Number(elValue)) ? 0 : Number(elValue);
if(isNegetive) elValue = 0 - elValue;
alert(elValue); //-1234990.234
You can use regular expression.
var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);
That will alert 2.
You can extract numbers from a string using a regex expression:
let string = "xxfdx25y93.34xxd73";
let res = string.replace(/\D/g, "");
console.log(res);
output: 25933473