Regular expressions:
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern )
This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.
To concatenate them:
'something102asdfkj1948948'.match( numberPattern ).join('')
Assuming you're not dealing with complex decimals, this should suffice I suppose.
Answer from meder omuraliev on Stack OverflowRegular expressions:
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern )
This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.
To concatenate them:
'something102asdfkj1948948'.match( numberPattern ).join('')
Assuming you're not dealing with complex decimals, this should suffice I suppose.
You could also strip all the non-digit characters (\D or [^0-9]):
let word_With_Numbers = 'abc123c def4567hij89'
let numbers = word_With_Numbers.replace(/\D/g, '');
console.log(numbers)
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Extract numbers from a string-Javascript - Code Review Stack Exchange
regex - How can I extract a number from a string in JavaScript? - Stack Overflow
regex - Extract all numbers from string in JavaScript - Stack Overflow
javascript regex - extract number from string - Stack Overflow
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.
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
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 */
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.
Use a regular expression.
const r = /\d+/;
const s = "you can enter maximum 500 choices";
alert (s.match(r));
The expression \d+ means "one or more digits". Regular expressions by default are greedy meaning they'll grab as much as they can. Also, this:
const r = /\d+/;
is equivalent to:
const r = new RegExp("\\d+");
See the details for the RegExp object.
The above will grab the first group of digits. You can loop through and find all matches too:
const r = /\d+/g;
const s = "you can enter 333 maximum 500 choices";
const m;
while ((m = r.exec(s)) != null) {
alert(m[0]);
}
The g (global) flag is key for this loop to work.
var regex = /\d+/g;
var string = "you can enter maximum 500 choices";
var matches = string.match(regex); // creates array from matches
document.write(matches);
References:
regular-expressions.info/javascript.html (archive)
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp (archive)
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
}