Extract (“get”) a number from a string

Extract (“get”) a number from a string

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.

Solutions/Answers:

Solution 1:

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>

Solution 2:

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

Solution 3:

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

Solution 4:

Using match function.

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

jsfiddle

Solution 5:

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

Solution 6:

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.