553

I have a string in JavaScript (e.g., #box2), and I just want the 2 from it.

I 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.

3
  • 1
    you can simply do like this . it will work well . var thestring = $(this).attr('href'); var thenum = parsefloat(thestring); alert(thenum); Jul 3, 2017 at 11:10
  • 2
    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.5 Aug 27, 2017 at 11:07
  • 1
    Related: stackoverflow.com/q/1862130/1066234
    – Avatar
    Jan 12, 2018 at 16:47

27 Answers 27

857

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"

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>

14
  • 23
    -1, "#box2_col3".replace( /^\D+/g, '') should have shown 2, not 2_col3. Apr 4, 2012 at 1:27
  • 2
    @shiplu.mokadd.im: I don't see any reference to #box2_col3 in the question.
    – georg
    Apr 4, 2012 at 1:30
  • 2
    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. Apr 4, 2012 at 1:33
  • 3
    in that case your pattern also fails if there is number before the end. Apr 4, 2012 at 1:40
  • 2
    You could make replace work with leading numbers by using: theString.replace(/^.*\D+/g, '');, but shiplu.mokadd.im's solution is better. Apr 4, 2012 at 2:35
332

You should try the following:

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

4
  • 3
    nice answer but what if I want the set of numbers separately. i.e. 1234, 5616133...
    – Amar Singh
    Dec 23, 2018 at 17:55
  • 3
    Or one-liner + parsing to integer: parseInt(txt.match(/\d/g).join(''), 10) Apr 19, 2019 at 11:52
  • " $ 20.0 ".match(/\d/g).join('') => "200" (just saying)
    – vsync
    Dec 19, 2019 at 9:41
  • 3
    this solution will not extract float. the regex should be /[+-]?\d+(\.\d+)?/g
    – Julfikar
    Apr 13, 2022 at 15:47
170

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

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

1
  • 9
    This is better than the accepted answer, since it does replace all non-numbers globally and btw, /[^0-9]/g can be replaced with /[^\d]/g.
    – CPHPython
    Mar 19, 2019 at 12:05
61

Using the match function.

var thenum = "0a1bbb2".match(/\d+$/)[0];
console.log(thenum);

7
  • 1
    Also you can add unary '+' to make it integer var thenum = +thestring.match(/\d+$/)[0]; Mar 5, 2014 at 7: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
    Jun 24, 2014 at 4:57
  • @nissemand Dont guess. Try yourself. Even you didn't see the fiddle. Jun 24, 2014 at 6:35
  • 1
    @YevgeniyAfanasyev it should not. Check the original question. Specially the last line. Number should be at the end. Apr 29, 2015 at 7:25
  • 1
    @hayley Check the return value of the match function in the MDN. May 5, 2022 at 10:35
47

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

var price = "£1,739.12";
parseFloat(price.replace(/[^\d\.]*/g, '')); // 1739.12
1
  • 3
    What if I want 1,739.12 ?
    – NoobCoder
    Sep 22, 2020 at 13:53
35

I tried all the combinations cited in the previous answer with this code and got it working. It 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 attribute, but whatever, the solution is better, because it’s more complete.

1
  • i think better will be str.match(/\d+/g).map(Number) it will return an array Nov 13, 2018 at 3:05
19

You may use the great parseInt() method.

It will convert the leading digits to a number:

parseInt("-10px");
// Will give you -10
2
  • 29
    this only works when the number is at the beginning of the string
    – Russj
    May 21, 2015 at 3:53
  • 4
    its returning NaN
    – Ahmed Syed
    Nov 8, 2017 at 9:34
16

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

Wrap it into a vanilla JavaScript function:

function onlyNumbers(text){
    return text.replace(/\D/g, "");
}
12

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

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

jsFiddle:

12

function justNumbers(string)
{
   var numsStr = string.replace(/[^0-9]/g, '');
   return parseInt(numsStr);
}

console.log(justNumbers('abcdefg12hijklmnop'));

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 won’t have it

12

To return an int from the string, you can do the following code. It removes all not number characters and returns an integer.

Number("strin[g]3".replace(/\D+/g, ""))
10

If you want to parse a number from a price like $6,694.20, it can be done this way:

parseFloat('$6,694.20'.replace(/^\D|,+/g, ''))

Or via a function:

function parsePrice(value) {
  return parseFloat(value.replace(/^\D|,+/g, ''))
}

parsePrice('$6,694.20') // 6694.2
1
  • Note that in case there may be more than one character at the beginning of the string which is not part of the number, you'll want to use value.replace(/^\D+|,+/g, '') Jan 20, 2023 at 20:32
8
let str = "Total Work Duration: 189.56 Hrs.Present: 23.5 Absent: 2";

/* The provided regex globally matches the character
   "." and a digit from the string */
let numArr = str.match(/[\d\.]+/g)

/* It returns an array [189.56, ., 23.5, 2], and
   uses the filter function to remove the '.' */
numArr = numArr.filter(n => n != '.')
console.log(numArr)
1
  • 3
    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – dpr
    Apr 21, 2022 at 8:11
6

You can use a regular expression.

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

That will alert 2.

1
  • 4
    -1 multiple digits will not be captured and for using array in alert Apr 4, 2012 at 1:24
5

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
4

You can use Underscore.js' string library as follows:

var common = "#box"
var href = "#box1"

_(href).strRight(common)

The result will be: 1

See: 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>

JavaScript code:

var comm = "#box"
$('a').click(function() {
  $('div').html(_($(this).attr('href')).strRight(comm))})

If you have a suffix as follows:

href="box1az"

You can use the following demo:

http://jsfiddle.net/abdennour/Vyqtt/1/

function retrieveNumber(all, prefix, suffix) {
  var left = _(all).strRight(prefix);
  return _(left).strLeft(suffix);
}
4

Here's a solution that checks for no data:

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

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

if (thenum != null)
{
    console.log(thenum[0]);
}
else
{
    console.log('Not a number');
}
3

Please check the below JavaScript code. There you can get only a number.

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

Output: 1234567789

3
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
2
  • 1
    Ad an explanation. E.g. why you use namely this regex.
    – mentallurg
    Jun 16, 2019 at 10:00
  • Where was this copied from? The misspelling "negetive" might be a good signature. Jan 23, 2023 at 0:48
2

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

var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);
0
2

Written without a regular expression:

// Without Regex

function extractNumber(string) {
  let numArray = string.split('').map(item => {
    if (typeof +item === 'number' && !isNaN(+item)) 
      return +item
  })
  return +numArray.join('')
}

extractNumber('@1200milion$')  // 1200

2
  • What are all the leading pluses (+) for? Jan 23, 2023 at 1:41
  • @PeterMortensen " + " is a shorthand to convert a string to number +item === Number(item) Jan 23, 2023 at 11:28
2

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 at http://ideone.com/iOCf5G.

1
  • 7
    java !== javascript - replaceAll does not exist in standard javascript. Only some libraries like jQuery have that method. In the future, you should clarify. Aug 12, 2015 at 8:59
1

You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:

    var color = $( this ).css( "background-color" );
    var r = parseInt(color.match(/\d+/g)[0]);
    var g = parseInt(color.match(/\d+/g)[1]);
    var b = parseInt(color.match(/\d+/g)[2]);
2
  • 1
    Hello! This question already has an accepted answer. Before looking at answered questions, please consider looking at unanswered ones first. If you do, however, have something to add to an answered question, please consider reading other answers thoroughly first.
    – PajLe
    Jul 8, 2020 at 2:33
  • Re ""(/\d+/g)" which will remove all non-number text": Really? It presumably comes with a qualification. That needs to be explained in the answer. (But ***** without ***** "Edit:", "Update:", or similar - the answer should appear as if it was written today) Jan 23, 2023 at 1:17
1

This answer will cover most of the scenarios. I came across this situation when a user tried to copy paste the phone number.

$('#help_number').keyup(function() {
  $(this).val().match(/\d+/g).join("")
});

Explanation:

str = "34%^gd 5-67 6-6ds"

str.match(/\d+/g)

It will give an array of strings as output:

["34", "56766"]

 

str.match(/\d+/g).join("")

join() will convert and concatenate that array data into a single string.

Output:

"3456766"

In my example, I needed the output as 209-356-6788, so I used replace():

$('#help_number').keyup(function() {
  $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/, '$1-$2-$3'))
});
2
1

In one of my projects I had to take a rating value from a string. This is what I used:

let text = '#xbox2'
let num = text.trim().
  split('').
  map(num => Number(num)).
  filter(x => Number.isInteger(x))
-1

Use:

changeStrangeDate(dateString: string) {
  var sum = 0;
  var numbers = dateString.match(/\d+/g);
  if (numbers.length > 1) {
    numbers.forEach(element => {
        sum += parseInt(element);
      }
    );
  }
  console.log(new Date(sum).toDateString());
  return new Date(sum).toUTCString();
}

You can do it like that and then call a function where you need it, with a parameter.

this.changeStrangeDate('/Date(1551401820000-0100)/');

Not the answer you're looking for? Browse other questions tagged or ask your own question.