[javascript] How can I extract a number from a string in JavaScript?

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.

This question is related to javascript regex string numbers

The answer is


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

}

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

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 function where you need, with parameter.

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

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

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


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

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

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

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

you may use great parseInt method

it will convert the leading digits to a number

parseInt("-10px");
// will give you -10

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

You can use regular expression.

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

That will alert 2.


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

This answer will cover most of the scenario. I can across this situation when user try 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 a array of string as output >> ["34", "56766"]

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

join will convert and concatenate that array data into single string

output >> "3456766"

In my example I need 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'))
  });

please check below javaScripts, there you can get only number

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

output : 1234567789


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


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

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


Using match function.

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

jsfiddle


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

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

jsFiddle:


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.


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

var price = "£1,739.12";
parseFloat(price.replace( /[^\d\.]*/g, '')); // 1739.12

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python