Regex using javascript to return just numbers
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.
Return only numbers from string
This is a great use for a regular expression.
var str = "Rs. 6,67,000"; var res = str.replace(/\D/g, ""); alert(res); // 667000
regex to get all number from a string?
You can extract out all number from your string using /\d+/g
and then join the result to get your new number.
var result = 'AAAA 1 BBBB 2'.match(/\d+/g);console.log(result.join(''));
Regex to allow only numbers and max 2 digits
I would recommend to update regex to allow 0 or 2 digits- /^[0-9]{0,2}$/
.
The following values will match: '', '0', '1', ... '10', ... '99'.
keypress
event has the following fields:
event.target.value
- value of input before new key was pressedevent.key
- string value of the key that was pressed
When event.target.value
and event.key
are combined together we can estimate new value of the input.
event.preventDefault()
call can be used to block keypress event if the resulting value does not match the needed pattern.
document.getElementById('myinput').addEventListener('keypress', event => {
if (!`${event.target.value}${event.key}`.match(/^[0-9]{0,2}$/)) {
// block the input if result does not match
event.preventDefault();
event.stopPropagation();
return false;
}
});
<input id="myinput" type="text" value="" />
How can I extract a number from a string in JavaScript?
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>
javascript regex - extract number from string
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])" />
Regex to check whether a string contains only numbers
var reg = /^\d+$/;
should do it. The original matches anything that consists of exactly one digit.
Javascript regular expression to allow only numbers upto 10 digits, string and special charecters are not allowed
Try using this regex:
var compare=/^[0-9]{1,10}$/g
Regex - Get Text/Numbers Only and Extra
.match()
returns an array, if there was a match. Thus to get the matched group you have to use [0]
on the result of .match()
before calling .replace()
.
go('Tree Log & Fire (TLF)');go('Leaves');go('River Moon (RM)');
function go(oldString) { var newString = oldString .match(/[^]+(?=(\s\())|.+/)[0] // <-- added [0] to get the 1st group's result str .replace(/[^A-Z0-9]+/ig, '-') .toLowerCase();
console.log(newString);}
Javascript Regex For only numbers and no white spaces
You could use /^\d+$/
.
That means:
^
string start\d+
a digit, once or more times$
string end
This way you force the match to only numbers from start to end of that string.
Example here: https://regex101.com/r/jP4sN1/1
jsFiddle here: https://jsfiddle.net/gvqzknwk/
Note:
If you are using the RegExp constructor you need to double escape the \
in the \d
selector, so your string passed to the RegExp constructor must be "^\\d+$"
.
So your function could be:
function ValidateNumber(strNumber) {
var regExp = new RegExp("^\\d+$");
var isValid = regExp.test(strNumber); // or just: /^\d+$/.test(strNumber);
return isValid;
}
Related Topics
Get the Value of Checked Checkbox
Force Download Through Js or Query
Es6 Array Destructuring Weirdness
Relation Between Commonjs, Amd and Requirejs
Send Message to Specific Client with Socket.Io and Node.Js
How to Scroll to Specific Item Using Jquery
Jquery.Inarray(), How to Use It Right
JSON.Stringify() Array Bizarreness with Prototype.Js
Using Jquery to Replace One Tag with Another
Idiomatically Find the Number of Occurrences a Given Value Has in an Array
How to Add a Tooltip to an Svg Graphic
Getting the Return Value of JavaScript Code in Selenium
What Does [Object Object] Mean? (Javascript)
How to Use Ajax to Do File Upload
Set a Cookie to Httponly via JavaScript
Manipulating Innerhtml Removes the Event Handler of a Child Element
JavaScript - Get Portion of Url Path
Find and Remove Objects in an Array Based on a Key Value in JavaScript