I'm using this regex to validate float numbers:
var reg = /\d+\.?\d+/;
But it's validating this as true:
"11.34x"
"11.34abs"
"1a1.34abs"
The \d should only match numbers. What is happening?
If you don't anchor the regular expression, it will match a string that contains a substring that matches.
Try:
var reg = /^\d+\.?\d+$/;
The ^ matches the start of the test string, and $ matches the end. Thus that regular expression will only match strings that have nothing but digits and at most one ".".
edit — as pointed out, your use of the + quantifier means your regex requires digits; if there's a decimal point, then it requires digits on both sides. Maybe that's what you want, maybe it isn't.
use this regular expression ^\d+(\.\d+)?$
or ^\d+([.,]\d+)?$ separator can be comma or dot
Consider using the Number wrapper/constructor function instead:
Number('11.34'); // => 11.34
Number('11.34x'); // => NaN
[Edit] As commenter #VisioN points out, that function has an edge case for empty and pure-whitespace strings, so maybe create a wrapper function:
function reallyParseFloatingPointNumber(s) {
var s = (''+s).trim();
return (s==='') ? NaN : Number(s);
}
if (!"12 34.98 ".replace(/^\s+|\s+$/g,"").match(/^\d+\.?\d+$/))
alert("Please enter numbers in float form")
else alert ("Good Form, Old Chap!")
Alas, I am mistaken again! burning_LEGION is correct:
/^\d+(\.\d+)?$/
will match single digits too.
Related
I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input
Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.
function returnFloat(str){
console.log(str.replace(/$,)( /g,""));
}
but when I call it:
returnFloat("($ 51,453,042.21)")
>>> ($ 51,453,042.21)
It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.
My plan B is ugly:
str = str.replace("$", "");
str = str.replace(",", "");
str = str.replace(",", "");
str = str.replace(" ", "");
str = str.replace("(", "");
str = str.replace(")", "");
console.log(str);
There are certain things in RegEx that are considered special regex characters, which include the characters $, ( and ). You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter
function toFloat(str){
return str.replace(/[\$,\(\)]/g,'');
}
console.log(toFloat('($1,234,567.90'));
Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.
the $ character means end of line, try:
console.log(str.replace(/[\$,)( ]/g,""));
You can fix your replacement as .replace(/[$,)( ]/g, "").
However, if you want to remove all letters that are not digit or dot,
and easier way exists:
.replace(/[^\d.]/g, "")
Here \d means digit (0 .. 9),
and [^\d.] means "not any of the symbols within the [...]",
in this case not a digit and not a dot.
if i understand correctly you want to have this list : 51,453,042.21
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21
if you want to delete ','
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21
I have this regular expression to test if an input starts with the letter "a" and is followed by 6 numbers. On the online validator seems to work, but on JavaScript doesnt.
This is the code:
function checkBookingReference (ref) {
var regex = /(^a|A)([0-9]{6})/;
return regex.test(ref);
}
The function returns true if I enter more than six numbers, and it shouldn't. Any idea why?
That regex will return true if anywhere in the string there is a match. If you want to ensure the entire string matches it, then you'll want to use ^ to match the beginning and $ to match the end.
/^(a|A)([0-9]{6})$/
This is how I would do it:
return /^A[0-9]{6}$/i.test(ref);
Use the regex object to specify the regular expression and then test it. Try this
var regex = new RegExp("^a([0-9]{6})$","i");
return regex.test(ref);
You nee to move the carat ^ outside the parentheses and use a proper group around the letters, then loose the trailing dollar sign $. Try this:
var regex = /^[aA][0-9]{6}/;
The parenthesis inside meant "not". Outside it means "beginning of string". The dollar sign meant "end of string".
I'm trying to use a regular expression in JavaScript to match a number or a number containing a decimal. The regular expression looks like [0-9]+ | [0-9]* \. [0-9]+.
However, for some reason this '1A'.match(/^[0-9]+|[0-9]*\.[0-9]+$/) incorrectly finds a match. I'm not sure which part of the expression is matching the A.
The problem is your alternation. This is what it says:
^[0-9]+ # match an integer at the start
| # OR
[0-9]*\.[0-9]+$ # match a decimal number at the end
So the first alternative matches.
You need to group the alternation:
/^(?:[0-9]+|[0-9]*\.[0-9]+)$/
The ?: is an optimisation and a good habit. It suppresses capturing which is not needed in the given case.
You could get away without the alternation as well, though:
/^[0-9]*\.?[0-9]+$/
Or even shorter:
/^\d*\.?\d+$/
'1A'.match(/^[0-9]+|[0-9]*\.[0-9]+$/) finds a match because it is a union of:
^[0-9]+
and
[0-9]*\.[0-9]+$
where the first matches.
to avoid this, group them: ^([0-9]+|[0-9]*\.[0-9]+)$
and try this:
'1A'.match(/^([0-9]+|[0-9]*\.[0-9]+)$/) === null
alternatively:
function matchExacly(str, regex) {
var tmp = str.match(regex);
return tmp ? tmp[0] === str : false;
}
matchExacly('1A', /[0-9]+|[0-9]*\.[0-9]+/) === false
matchExacly('1', /[0-9]+|[0-9]*\.[0-9]+/) === true
Maybe I am at the wrong place but if you use regex just for validating numeric values, why not to use faster alternatives, as the following:
var isNumber = ( +n === parseFloat(n) );
I have a string that looks like this: [~21~]. How can I use regex to only return 21? The number can be any value (numbers), at any length. I am using Javascript with this regex, so if you could include that in your exsample, that would be great.
Thomas
You can:
Remove any other characters than digits
Parse the resulting number to a real number instead of a string
Like:
var number = parseInt(str.replace(/[\D]/g, ""), 10);
Where:
parseInt(..., 10) parses any string to a number in base 10
str.replace(..., "") will remove characters (replace them with nothing)
[\D] means: anything except digits
For example,
parseInt("[~21~]".replace(/[\D]/g, ""), 10) === 21;
Note that it will concatenate numbers in e.g. [~21~22~]; that will become 2122.
A simple regex that will work in your case is:
[0-9]+
This will match a sequence of strings consisting of the characters: 0,1,2,3,4,5,6,7,8,9
If you aren't worried about error-handling:
var getTheNumber = function(a) { return a.substring(0, a.length-2).substring(2); }
-*\d+(\.\d+)*
Contemplates negative and/or decimal numbers. This will extract any number of 1 or more digits no matter the string.