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>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
You should try the following:
var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
console.log(numb);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
+myString.replace(/[^\d.ex-]+/gi, '')
strips out all characters that cannot appear in a JavaScript number, and then applies the + operator to it to convert it to a number. If you don't have numbers in hex format or exponential format then you can do without the ex.
EDIT:
To handle locales, and handle numbers in a more tailored way, I would do the following
// Get rid of myriad separators and normalize the fraction separator.
if ((0.5).toLocaleString().indexOf(',') >= 0) {
myString = myString.replace(/\./g, '').replace(/,/g, '.');
} else {
myString = myString.replace(/,/g, '');
}
var numericValue = +(myString.match(
// Matches JavaScript number literals excluding octal.
/[+-]?(?:(?:(?:0|[1-9]\d*)(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|0x[0-9a-f]+)/i)
// Will produce NaN if there's no match.
|| NaN);
Your case requires a Regular Expression, because all native number-converting methods fail when the string is prefixed by a non-digit/dot.
var string = '$1.22'; //Example
string = string.replace(/[^0-9.]+/g, '');
// string = '1.22'
If you want to convert this string to a digit, afterwards, you can use parseInt, +, 1*.
For a comparison of these number-converting methods, see this answer
This is a great use for a regular expression.
var str = "Rs. 6,67,000";
var res = str.replace(/\D/g, "");
alert(res); // 667000
\D matches a character that is not a numerical digit. So any non digit is replaced by an empty string. The result is only the digits in a string.
The g at the end of the regular expression literal is for "global" meaning that it replaces all matches, and not just the first.
This approach will work for a variety of input formats, so if that "Rs." becomes something else later, this code won't break.
For this task the easiest way to do it will be to us regex :)
var input = "Rs. 6,67,000";
var res = input.replace(/\D/g,'');
console.log(res); // 667000
Here you can find more information about how to use regex:
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
I hope it helped :)
Regards
Try match()
var text = "top 50 right 100 left 33";
var arr = text.match(/[0-9]{1,3}/g);
console.log(arr); //Returns an array with "50", "100", "33"
You can also use [\d+] (digits) instead of [0-9]
Place this string in a var, if you know every number will be seperated by a space you can easely do the following:
var string = "top 50 left 100";
// split at the empty space
string.split(" ");
var numbers = new Array();
// run through the array
for(var i = 0; i < string.length; i++){
// check if the string is a number
if(parseInt(string[i], 10)){
// add the number to the results
numbers.push(string[i]);
}
}
Now you can wrap the whole bit in a function to run it at any time you want:
function extractNumbers(string){
var temp = string.split(" ");
var numbers = new Array();
for(var i = 0; i < temp.length; i++){
if(parseInt(temp[i], 10)){
numbers.push(temp[i]);
}
}
return numbers;
}
var myNumbers = extractNumbers("top 50 left 100");
Update
After reading @AmirPopovich s answer, it helped me to improve it a bit more:
if(!isNaN(Number(string[i]))){
numbers.push(Number(string[i]));
}
This will return any type of number, not just Integers. Then you could technically extend the string prototype to extract numbers from any string:
String.prototype.extractNumbers = function(){ /*The rest of the function body here, replacing the keyword 'string' with 'this' */ };
Now you can do var result = "top 50 right 100".extractNumbers();
Correct way:
var str = '12 3 44 5 \n 7 88';
//if there matches, store them into the array, otherwise set 'numbers' to empty array
var numbers = str.match(/\d+/g)?str.match(/\d+/g):[];
//to convert the strings to numbers
for(var i=0;i<numbers.length;i++){
numbers[i]=+numbers[i]
}
alert(numbers);
Why? .match() is just an easier thing to use there. \d+ gets a number of any length, flag g returns all the matches, not only the first match.
If you also want to match the floats, the regex would be /\d+([\.,]\d+)?/g. It'll also match 42,12 or 42.12.
A possible alteranative
var s = '12 3 44 5 \n 7 88';
var numbers = s.split(/[^\d]+/).map(Number);
document.getElementById('out').textContent = JSON.stringify(numbers);
console.log(numbers);
<pre id="out"></pre>
With split you will never have a situation like where exec or match could be null
Note: this does not take into account negative numbers or floating point or scientific numbers etc. An empty string will also produce [0], so specification is key.
Here's an example function that will return an array representing the two numbers, or null if there wasn't a match:
function extractNumbers(str) {
var m = /(\d+)to(\d+)/.exec(str);
return m ? [+m[1], +m[2]] : null;
}
You can adapt that regular expression to suit your needs, say by making it case-insensitive: /(\d+)to(\d+)/i.exec(str).
You can use a regular expression to find it:
var str = "sure1to3";
var matches = str.match(/(\d+)to(\d+)/);
if (matches) {
// matches[1] = digits of first number
// matches[2] = digits of second number
}
You could use a regular expression for it. It looks only for connected numbers.
console.log('(235+456+2+3-6-(2*5))'.match(/\d+/g));
The solution using String.match function:
var str="(235+456+2+3-6-(2*5))"
numbers = str.match(/\b\d+?\b/g);
console.log(numbers); // ["235", "456", "2", "3", "6", "2", "5"]
You can get it like this:
var suffix = 'comment_like_123456'.match(/\d+/); // 123456
With respect to button:
$('.comment_like').click(function(){
var suffix = this.id.match(/\d+/); // 123456
});
You can try this. it will extract all number from any type of string.
var suffix = 'comment_like_6846511';
alert(suffix.replace(/[^0-9]/g,''));
DEMO
This will get all the numbers separated by coma:
var str = "10 is smaller than 11 but greater then 9"; var pattern = /[0-9]+/g; var matches = str.match(pattern);
After execution, the string matches will have values "10,11,9"
If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10
(There is no need for JQuery)
This uses regular expressions and the exec method:
var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];
The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.
You can use a regex to get the first integer :
var num = parseInt(str.match(/\d+/),10)
If you want to parse any number (not just a positive integer, for example "asd -98.43") use
var num = str.match(/-?\d+\.?\d*/)
Now suppose you have more than one integer in your string :
var str = "a24b30c90";
Then you can get an array with
var numbers = str.match(/\d+/g).map(Number);
Result : [24, 30, 90]
For the fun and for Shadow Wizard, here's a solution without regular expression for strings containing only one integer (it could be extended for multiple integers) :
var num = [].reduce.call(str,function(r,v){ return v==+v?+v+r*10:r },0);
parseInt('asd98'.match(/\d+/))
Just use a simple regex:
const input = 'this is a signal , entry : 2430 and side is short';
const number1 = input.match(/entry\W+(\d+)/)?.[1]; // "2430"
const number2 = input.match(/santa\W+(\d+)/)?.[1]; // undefined
You can also do with indexOf and regular expression
const word = "entry";
const str = "this is a signal , entry : 2430 and side is short";
const index = str.indexOf(word);
if (index !== -1) {
let result = str.slice(index + word.length).match(/\d+/)[0];
console.log(result);
}
Your RegEx works, if you want single digit right after /
Your regex \d+\/(\d)\d\d\d will match digits / then four digits and add first digit after slash in captured group.
Note that 0th captured group will contain complete matched string. g flag is not necessary as there is only one instance of numbers in that pattern.
You can use this regex, but use first index to get the digit right after slash.
'1/2009'.match(/\d+\/(\d)\d\d\d/g)[1]
^ : Get me the value from first captured group.
And this regex can be optimized to below
.match(/\/(\d)/)[1]
This will match the number followed by /. And use the first captured group to extract the number.
<input type="text" onblur="console.log(this.value.match(/\/(\d)/)[1])" />
To get all digits after /
Just add + quantifier to \d in the captured group.
.match(/\/(\d+)/)[1]
Try
var string = "1/2009 stay longer";
console.log(string.match(/\/(\d+)/)[1]);
\d+ matches one or more digits. If you're only interested in capturing the digit right after /, use string.match(/\/(\d)/ instead.
I used the following regexp to extract numbers from a string:
var string = "border-radius:10px 20px 30px 40px";
var numbers = string.match(/\d+/g).map(Number);
The code will fail in below cases:
- Negative numbers
- Decimal numbers
- Units other than
px(e.g.pt,%,vw,vh, ...)
Moreover, the numbers array contains space before numbers and an empty string at the end which is not required.
I recommend to use below regex to extract numbers from strings
/[+-]?\d+(?:\.\d+)?/g
[+-]?: Optional+or-sign before number\d+: Match one or more numbers(?:\.\d+)?: Optional decimal point.?:denotes non-capturing group.gflag: To get all matches
After the numbers are extracted from string, they can be converted to Number format.
var regex = /[+-]?\d+(?:\.\d+)?/g;
var str = `padding: 0;
font-size: 16pt;
width: 50%;
height: 20vh;
margin-right: 12px;
padding-right: -12.5px;`;
var match;
while (match = regex.exec(str)) {
console.log(match[0]);
}
Here's online demo of the regex on Regex101.
var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"
Yes, match is the way to go:
var matches = str.match(/(\d+)sl(\d+)/);
var number1 = Number(matches[1]);
var number2 = Number(matches[2]);
If the string is always going to look like this: "ch[num1]sl[num2]", you can easily get the numbers without a regex like so:
var numbers = str.substr(2).split('sl');
//chop off leading ch---/\ /\-- use sl to split the string into 2 parts.
In the case of "ch2sl4", numbers will look like this: ["2", "4"], coerce them to numbers like so: var num1 = +(numbers[0]), or numbers.map(function(a){ return +(a);}.
If the string parts are variable, this does it all in one fell swoop:
var str = 'ch2fsl4';
var numbers = str.match(/[0-9]+/g).map(function(n)
{//just coerce to numbers
return +(n);
});
console.log(numbers);//[2,4]
If you want to not include the dot, a look-ahead would make sense:
/[-+]?\d*(\.(?=\d))?\d+/g
Another option is to move the second \d+ inside the parentheses:
/[-+]?\d+(\.\d+)?/g
This rx gets numbers represented in strings, with or without signs, decimals or exponential format-
rx=/[+-]?((.\d+)|(\d+(.\d+)?)([eE][+-]?\d+)?)/g
String.prototype.getNums= function(){
var rx=/[+-]?((\.\d+)|(\d+(\.\d+)?)([eE][+-]?\d+)?)/g,
mapN= this.match(rx) || [];
return mapN.map(Number);
};
var s= 'When it is -40 degrees outside, it doesn\'t matter that '+
'7 roses cost $14.35 and 7 submarines cost $1.435e+9.';
s.getNums();
/* returned value: (Array) -40, 7, 14.35, 7, 1435000000 */
You could use a regex:
var foo = '2x32';
var matches = foo.match(/^(\d+)x(\d+)$/);
if (matches.length > 2) {
var a = matches[1]; // = 2
var b = matches[2]; // = 32
}
var str = "2x2";
var numbers = str.split("x"); // ["2","2"]
var first = numbers[0]; // "2"
Or, for short
"2x2".split("x")[0]; // "2"