Extract ("get") a number from a string

Go To StackoverFlow.com

272

I have a string in javascript like `#box2' and I just want the '2' from it.

Tried:

var thestring = $(this).attr('href');
var thenum = thestring.replace( /(^.+)(\w\d+\w)(.+$)/i,'$2');
alert(thenum);

It still returns #box2 in the alert, how can I get it to work?

It needs to accommodate for any length number attached on the end.

2012-04-04 01:14
by user1022585
you can simply do like this . it will work well .

var thestring = $(this).attr('href');

var thenum = parsefloat(thestring);

alert(thenum) - Vivek Shukla 2017-07-03 11:10

this code works fine for me but for one case , I have a string '2.5/mile' and I want to extract 2.5 out of this. Above code gives me 25 instead of 2. - Bijay Singh 2017-08-27 11:07
Related: https://stackoverflow.com/q/1862130/106623 - Kai Noack 2018-01-12 16:47


466

For this specific example,

 var thenum = thestring.replace( /^\D+/g, ''); // replace all leading non-digits with nothing

in the general case:

 thenum = "foo3bar5".match(/\d+/)[0] // "3"

Since this answer gained popularity for some reason, here's a bonus: regex generator.

function getre(str, num) {
  if(str === num) return 'nice try';
  var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
  for(var i = 0; i < res.length; i++)
    if(str.replace(res[i], '') === num) 
      return 'num = str.replace(/' + res[i].source + '/g, "")';
  return 'no idea';
};
function update() {
  $ = function(x) { return document.getElementById(x) };
  var re = getre($('str').value, $('num').value);
  $('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>

2012-04-04 01:16
by georg
-1, "#box2_col3".replace( /^\D+/g, '') should have shown 2, not 2_col3 - Shiplu Mokaddim 2012-04-04 01:27
@shiplu.mokadd.im: I don't see any reference to #box2_col3 in the question - georg 2012-04-04 01:30
Yes there is no reference of #box2_col3. But see the regex OP used (\w)(.+$))which clearly indicates there are other characters after the number - Shiplu Mokaddim 2012-04-04 01:33
@shiplu.mokadd.im: read the question again: "number attached on the end" - georg 2012-04-04 01:35
in that case your pattern also fails if there is number before the end - Shiplu Mokaddim 2012-04-04 01:40
You could make replace work with leading numbers by using: theString.replace(/^.*\D+/g, '');, but shiplu.mokadd.im's solution is better - LandonSchropp 2012-04-04 02:35
how about there are two number in a string? eg: [55-57 - Muhaimin 2014-06-11 23:58
var thenum = thestring.replace( /[^\d]+/g, '') - w4kskl 2014-08-14 08:58
Is there a point of extracting a number from a string if you already have the number? Seems otherwise you would just search for a contained string to see if its there. Seems it'd be more useful without putting in a particular number to extract - liljoshu 2016-07-20 19:57
you do not need ^ as I think: .replace(/\D+/g, '')Undefitied 2016-12-13 14:44
\D mist be \d then work. When I use \D, I got NAH to numbe - Thilina Sampath 2017-04-20 04:23


177

You should try the following:

var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);​

result

1234561613213213
2013-01-04 20:37
by Jason Marshall
Perfect Answer - hamzox 2018-03-20 07:55
loved that answe - WasiF 2018-07-10 12:09
nice answer but what if I want the set of numbers separately. i.e. 1234, 5616133.. - Yo Yo 2018-12-23 17:55
Awesome!!!!! ; - Jcc.Sanabria 2019-01-24 20:21


56

I think this regular expression will serve your purpose:

var num = txt.replace(/[^0-9]/g,'');

Where txt is your string.

It basically rips off anything that is not a digit.

I think you can achieve the same thing by using this as well :

var num = txt.replace(/\D/g,'');
2013-10-21 13:47
by klikas
/[^0-9]/g +1 for readability. Also used with most of the answers here: https://stackoverflow.com/q/1862130/106623 - Kai Noack 2018-01-12 16:47
Love that answer, thanks! : - Emilia Szymańska 2019-03-01 10:50


51

Using match function.

var thenum = thestring.match(/\d+$/)[0];
alert(thenum);

jsfiddle

2012-04-04 01:19
by Shiplu Mokaddim
Also you can add unary '+' to make it integer var thenum = +thestring.match(/\d+$/)[0] - Sergey Onishchenko 2014-03-05 07:00
I guess this doesn't work for > 1 digit numbers? (I understand the question was for 1 digit numbers, but I'm looking at numbers possible > 10. - Felix 2014-06-24 04:57
@nissemand Dont guess. Try yourself. Even you didn't see the fiddle - Shiplu Mokaddim 2014-06-24 06:35
Love this. A simplest way to extract the number into a variable without touch or modify the element. I would appreciate a combo with each for a multple coincidences inside a string. ie the string 12a55 report the last number, not all - erm3nda 2015-02-25 00:14
It does not work for the string like "#box21a - Yevgeniy Afanasyev 2015-04-29 05:26
@YevgeniyAfanasyev it should not. Check the original question. Specially the last line. Number should be at the end - Shiplu Mokaddim 2015-04-29 07:25
You are right. The answer in valid - Yevgeniy Afanasyev 2015-04-30 01:02


39

Try the following: string.replace(/[^0-9]/g, ''); This will delete all non-digit characters, leaving only digits in the string

function retnum(str) { 
    var num = str.replace(/[^0-9]/g, ''); 
    return parseInt(num,10); 
}

console.log('abca12bc45qw'.replace(/[^0-9]/g, ''));
console.log('#box2'.replace(/[^0-9]/g, ''));

2015-06-12 05:12
by xbalaji


31

Tried all the combinations cited above with this Code and got it working, was the only one that worked on that string -> (12) 3456-7890

var str="(12) 3456-7890";
str.replace( /\D+/g, '');

Result: "1234567890"

Obs: i know that a string like that will not be on the attr but whatever, the solution is better, because its more complete.

2014-01-28 16:12
by Paulo Roberto
i think better will be str.match(/\d+/g).map(Number) it will return an arra - Artem Bernatskyi 2018-11-13 03:05


26

And this is a snippet which extracts prices with currency and formatting:

var price = "£1,739.12";
parseFloat(price.replace( /[^\d\.]*/g, '')); // 1739.12
2015-12-16 11:56
by Lacho Tomov


11

you may use great parseInt method

it will convert the leading digits to a number

parseInt("-10px");
// will give you -10
2014-05-14 09:05
by Eugene Tiurin
this only works when the number is at the beginning of the strin - Russj 2015-05-21 03:53
its returning Na - Mujahed AKAS 2017-11-08 09:34


6

For a string such as #box2, this should work:

var thenum = thestring.replace(/^.*(\d+).*$/i,'$1');

jsFiddle:

2012-04-04 01:19
by icyrock.com


4

You can use regular expression.

var txt="some text 2";
var numb = txt.match(/\d/g);
alert (numb);

That will alert 2.

2012-04-04 01:20
by Robby Shaw
-1 multiple digits will not be captured and for using array in aler - Shiplu Mokaddim 2012-04-04 01:24


4

With Regular Expressions, how to get numbers from a String, for example:

String myString = "my 2 first gifts were made by my 4 brothers";
myString = myString .replaceAll("\\D+","");
System.out.println("myString : " + myString);

the result of myString is "24"

you can see an example of this running code here: http://ideone.com/iOCf5G

2015-07-15 18:07
by Elenasys
java !== javascript - replaceAll does not exist in standard javascript. Only some libraries like jQuery have that method. In the future, you should clarify - Levi Roberts 2015-08-12 08:59


3

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);

}
2013-05-07 14:38
by Abdennour TOUMI


1

Here's a solt. that checks for no data

var someStr = 'abc'; // add 123 to string to see inverse

var thenum = someStr.match(/\d+/);

if (thenum != null )
{
    console.log(thenum[0]);
}
else
{
 console.log('no number');
}
2015-07-31 23:00
by Gene Bo


1

Use this one-line code to get the first number in a string without getting errors:

var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
2015-10-08 12:32
by Ruslan


1

please check below javaScripts, there you can get only number

var txt = "abc1234char5678#!9";
var str = txt.match(/\d+/g, "")+'';
var s = str.split(',').join('');
alert(Number(s));

output : 1234567789

2017-04-20 04:43
by Thilina Sampath