How do I use JavaScript regex to validate numbers like this?
1,000
1,000.00
1000.00
1000
I tried this (the string used should not match):
test('2342342342sdfsdfsdf');
function test(t)
{
alert(/\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d/.test(t));
}
but still gives me true.
If you want to test if the complete input string matches a pattern, then you should start your regex with ^ and end with $. Otherwise you are just testing if the input string contains a substring that matches the given pattern.
^ means "Start of the line"
$ means "End of the line"
In this case it means you have to rewrite you regex to:
/^(\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d)$/
If you would omit the extra parentheses, because otherwise the "|" would have lower precedence than the ^ and $, so input like "1,234.56abc" or "abc.12" would still be valid.
I'm not sure what you mean by validate. But this might work.
//console.log is used in firebug.
var isNumber = function( str ){
return !isNaN( str.toString().replace(/[,.]/g, '') );
}
console.log( isNumber( '1,000.00' ) === true );
console.log( isNumber( '10000' ) === true );
console.log( isNumber( '1,ooo.00' ) === false );
console.log( isNumber( 'ten' ) === false );
console.log( isNumber( '2342342342sdfsdfsdf') === false );
try this
var number = '100000,000,000.00';
var regex = /^\d{1,3}(,?\d{3})*?(.\d{2})?$/g;
alert(regex.test(number));
Related
Why everything between / and / is going to print? It should give me error in console.
console.log normally print string enclosed within "" or any variable and object, in below case i am not passing string or any variable and object, but still it is printable.
var x = 10;
console.log(/m/);
console.log(/c/);
console.log(/&/);
console.log(/var/);
console.log(/x/);
Anything between / and / is considered to be regex. So, that's why it prints them out.
If you do a console.log( typeof /test/ ); it'll say Object which means that it is something.
JavaScript allows you to use the RegExp short hand like - /test/ which will match the string test in any given sequence.
Try something like:
let testOne = /test/;
let testTwo = new RegExp( 'test' );
console.log( testOne.test( 'test' ) );
console.log( testTwo.test( 'test' ) );
the code will output:
true
true
P.S.: The function regExp.test( String ) returns true if the String inside matches the expression defined in the regExp object.
Below is my code..
/(?!\*)/.test("test*test")
The result still return true.
I want to validate the string which will return false if any * in string.
Something is wrong with code?
Your regex returns true because it matches the starting position. The test you have just says "is there a position that is not followed by a *?" which literally any string will match - even "*" matches because after the * there is a position that is not followed by a(nother) *.
If you want to test if a string does not contain a *, the simplest solution is:
"test*test".indexOf("*") < 0 // true if no * in string
Doing so with regex would be something like:
/^[^*]*$/.test("test*test")
But that's more work.
Simply test for presence of * and negate the output
var string="123*456";
console.log( !(/\*/.test(string)) );
false
var string="12*34*56";
console.log( !(/\*/.test(string)) );
false
var string="123456";
console.log( !(/\*/.test(string)) );
true
I've encountered this weird behavior:
I'm on a breakpoint (variables don't change). At the console you can see, that each time I try to evaluate regexp methods on the same unchanging variable "text" I get these opposite responses. Is there an explanation for such thing?
The relevant code is here:
this.singleRe = /<\$([\s\S]*?)>/g;
while( this.singleRe.test( text ) ){
match = this.singleRe.exec( text );
result = "";
if( match ){
result = match[ 1 ].indexOf( "." ) != -1 ? eval( "obj." + match[ 1 ] ) : eval( "value." + match[ 1 ] );
}
text = text.replace( this.singleRe , result );
}
When you use regex with exec() and a global flag - g, a cursor is changing each time, like here:
var re = /\w/g;
var s = 'Hello regex world!'
re.exec(s); // => ['H']
re.exec(s); // => ['e']
re.exec(s); // => ['l']
re.exec(s); // => ['l']
re.exec(s); // => ['o']
Note the g flag! This means that regex will match multiple occurencies instead of one!
EDIT
I suggest instead of using regex.exec(string) to use string.match(regex) if possible. This will yield an array of occurences and it is easy to inspect the array or to iterate through it.
How can I form a regular expression that match the unique numbers that repeat in a repeating decimals?
Currently my regular expressions is the following.
var re = /(?:[^\.]+\.\d*)(\d+)+(?:\1)$/;
Example:
// Pass
deepEqual( func(1/111), [ "0.009009009009009009", "009" ] );
// Fails, since func(11/111) returns [ "0.099099099099099", "9" ]
deepEqual( func(11/111), [ "0.099099099099099", "099" ] );
Live demo here: http://jsfiddle.net/9dGsw/
Here's my code.
// Goal: Find the pattern within repeating decimals.
// Problem from: Ratio.js <https://github.com/LarryBattle/Ratio.js>
var func = function( val ){
var re = /(?:[^\.]+\.\d*)(\d+)+(?:\1)$/;
var match = re.exec( val );
if( !match ){
val = (val||"").toString().replace( /\d$/, '' );
match = re.exec( val );
}
return match;
};
test("find repeating decimals.", function() {
deepEqual( func(1), null );
deepEqual( func(1/10), null );
deepEqual( func(1/111), [ "0.009009009009009009", "009" ] );
// This test case fails...
deepEqual( func(11/111), [ "0.099099099099099", "099" ],
"What's wrong with re in func()?" );
deepEqual( func(100/111), [ "0.9009009009009009", "009"] );
deepEqual( func(1/3), [ "0.3333333333333333", "3"]);
});
Ok. I somewhat solved my own problem by taking Joel's advice.
The problem was that the regular expression section, (\d+)+(?:\1)$, was matching the pattern closest to the end of the string, which made it return "9", instead of "099" for the string "0.099099099099099".
The way I overcame this problem was by setting the match length to 2 or greater, like so.
(\d{2,})+(?:\1)$,
and filtering the result with /^(\d+)(?:\1)$/, incase that a pattern is stuck inside a pattern.
Here's the code that passes all my test cases.
Live Demo: http://jsfiddle.net/9dGsw/1/
var func = function( val ){
val = (val || "").toString();
var RE_PatternInRepeatDec = /(?:[^\.]+\.\d*)(\d{2,})+(?:\1)$/,
RE_RepeatingNums = /^(\d+)(?:\1)$/,
match = RE_PatternInRepeatDec.exec( val );
if( !match ){
// Try again but take off last digit incase of precision error.
val = val.replace( /\d$/, '' );
match = RE_PatternInRepeatDec.exec( val );
}
if( match && 1 < match.length ){
// Reset the match[1] if there is a pattern inside the matched pattern.
match[1] = RE_RepeatingNums.test(match[1]) ? RE_RepeatingNums.exec(match[1])[1] : match[1];
}
return match;
};
Thank you for everyone that helped.
Use: var re = /^(?:\d*)\.(\d{1,3})(?:\1)+$/
I have defined the min/max length with {min,max} of the repeating decimal because otherwise 009009009 would match in the first test case as well. Maybe it is still not the final solution, but at least a hint.
Silly question, but I do not know how to find (2000) into a regular expression and replace it with [2000]
You can do:
str.replace(/\((\d+)\)/g, "[$1]");
Regex used: \((\d+)\)
( and ) are special char in regex
used for grouping, to match literal
( ), you need to escape them as
\( \)
\d is short for a digit. \d+
means one or more digits.
( ) is to group and remember the
number. The remembered number will
later be used in replacement.
g for global replacement. Mean
every occurrence of the patten in the
string will be replaced.
$1 is the number between (
)that was grouped and remembered.
/ / are the regex delimiters.
function _foo(str) {
return str.replace(/[(](\d*)[)]/, '[$1]');
}
alert( _foo("(2000)") ); // -> '[2000]'
alert( _foo("(30)") ); // -> '[30]'
alert( _foo("(abc)") ); // -> '(abc)'
alert( _foo("()") ); // -> '[]'
Like this: yourString.replace(/\(2000\)/, "[2000]");
Try this:
function foo(S) {
return S.replace(/\(([^\)]+)\)/g,"[$1]");
}