Javascript RegExp.test allways returns true - javascript

I would like to create a javascript regex to test a string that would accept only characters from 0 to 9, a to z, A to Z and the followings chars: + * . for a total length between 1 and 10 characters.
I did this :
var reg = /[0-9A-Za-z\+\*\.]{1,12}/;
if(!reg.test($('#vat_id').val())) {
return false;
}
but this doesn't seem to work.
I tested it on http://www.regular-expressions.info/javascriptexample.html, I can input "$av" and it returns me "successful match"
where is the mistake ?
edit : the regex seems good now :
var reg = /^[0-9A-Za-z\+\*\.]{1,10}$/;
But why i can't make it work ?
see http://jsfiddle.net/R2WZT/

If you don't "anchor" the regular expression to indicate that matches should start at the beginning and end at the end of the test string, then that is taken to mean that you want to see if the pattern can be found anywhere in the string.
var reg = /^[0-9A-Za-z\+\*\.]{1,12}$/;
With ^ at the beginning and $ at the end, you indicate that the entire string must match the pattern; that is, that no characters appear in the string other than those that contribute to the match.

You're not setting it to match the start and end:
var reg = /^[0-9A-Za-z\+\*\.]{1,10}$/;

Related

Allowed Characters Regex (JavaScript)

I'm trying to build a regex which allows the following characters:
A-Z
a-z
1234567890
!##$%&*()_-+={[}]|\:;"'<,>.?/~`
All other characters are invalid. This is the regex I built, but it is not working as I expect it to. I expect the .test() to return false when an invalid character is present:
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*/g
return regex.test(string);
}
In this case, the test is always returning "true", even when "^" is present in the string.
Your regex only checks that at least one of the allowed characters is present. Add start and end anchors to your regex - /^...$/
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g
return regex.test(string);
}
... another approach, is instead of checking all characters are good, to look for a bad character, which is more efficient as you can stop looking as soon as you find one...
// return true if string does not (`!`) match a character that is not (`^`) in the set...
return !/[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/.test()
Instead of searching allowed characters search forbidden ones.
var string = 'abcd^wyd';
function regTest (string) {//[^ == not
var regex = /[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/g
return !regex.test(string);//false if found
}
console.log(regTest(string));
The regex, as you've written is checking for the existence of the characters in the input string, regardless of where it appears.
Instead you need to anchor your regex so that it checks the entire string.
By adding ^ and $, you are instructing your regex to match only the allowed characters for the entire string, rather than any subsection.
function isValidPassword (pwd) {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g\;
return regex.test(pwd);
}
alert(isValidPassword('abcd^wyd'));
Your regexp is matching the first part of o=your string i.e. "abcd" so it is true . You need to anchor it to the start (using ^ at the beginning) and the end of the string (using $ at the end) so your regexp should look like:
^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]$
That way it will need to match the entire string.
You can visualize it in the following link:
regexper_diagram
This regex will work.
var str = 'eefdooasdc23432423!##$%&*()_-+={[}]|:;"\'<,>.?/~\`';
var reg = /.|\d|!|#|#|\$|%|&|\*|\(|\)|_|-|\+|=|{|\[|}|]|\||:|;|"|'|<|,|>|\.|\?|\/|~|`/gi;
// test it.
reg.test(str); //true
I use this site to test my regex.
Regex 101

Validating Currency on Javascript using a regex not working

I need a regular expression for currency type.
Requirements :
1. First char can be a '$'. It can appear either 0 or 1 times.
2. Then a digit can appear multiple times.
3. Then a decimal point can appear either 0 or 1 time.
4. After this, a digit can appear 0 or more times.
I have written the following regular expression :
\$?\d+\.?\d*
I need to test this on JS . This is how i test this on JS;
var str = "$cng";
var patt = new RegExp('[\$?\d+\.?\d*]');
var res = patt.test(str);
console.log(res);
The above string $cng is returning true. I am not able to get it. Am i missing anything here. Can anyone please help. Thanks in advance.
You must need to escape all the backslashes one more times when passing it to the RegExp constructor which has double quotes as delimiter.
And also i suggest you to remove the square brackets around your pattern.
So change your pattern like below,
var patt = new RegExp("^\\$?\\d+\\.?\\d*$");
OR
var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
Example:
> var str = "$123.12";
undefined
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test(str);
true
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test('$123.12$');
false
Replace RegExp('[\$?\d+\.?\d*]') with RegExp(/\$?\d+\.?\d*/) and it will work as expected.
Working Code Snippet:
var str = "$100.10";
var patt = new RegExp(/^\$?\d+\.?\d*$/);
var res = patt.test(str);
console.log(res);
EDIT:
You can also simply do: var res = /^\$?\d+\.?\d*$/.test(str);
Your regular expression should also match the beginning and end of the string, otherwise it will only test if the string contains a currency:
^\$?\d+\.?\d*$
You added brackets around the regular expression when you implemented it in Javascript, which changes the meaning entirely. The pattern will find a match if any of the characters within the brackets exist in the string, and as there is a $ in the string the result was true.
Also, when you have a regular expression in a string, you have to escape the backslashes:
var patt = new RegExp('^\\$?\\d+\\.?\\d*$');
You can also use a regular expression literal to create the object:
var patt = /^\$?\d+\.?\d*$/;
You might want to change the requirements so that the decimal point only is allowed if there are digits after it, so that for example $1. is not a valid value:
^\$?\d+(\.\d+)?$
[\$?\d+\.?\d*]==>[] is a character class.
Your regex will just match 1 character out of the all defined inside the character class.
Use
^\\$?\\d+\\.?\\d*$
or
/^\$?\d+\.?\d*$/
to be very safe.

Regular expression matching javascript

I have a variable which can get any of the below values. x represents any alphanumeric character and the string can be of any length
/xxxxxxx
/xxxx/xxxx?xxx=xx
/xxxxx/
/xxxxxxxxx?
/xxxxxxx/xxxx/xxx
/xx/xxx.jpg
/xxx/xxxx/xxxx/xxxx
/xxx/xxxx/xxx/xxx/xxxx
/xxxx?xx=yy&abc=def&xyz=lmn
The goal is to get everything before the "?" character in the string if ? character exists
if it doesn't exist then it should simply get the string
i have written a regular expression as follows:
var pattern = /\/.*\?/;
The only issue is this pattern does not stop at the ? and return the whole string. Any clues how this can be fixed ?
The goal is to get everything before the "?" character in the string if ? character exists if it doesn't exist then it should simply get the string
/^[^?]*/
This works because ^ means start of input, and [^?] means a character that is not a ?, and * means zero or more, so the whole means "starting from input, zero or more characters that are not question marks".
That has the effect of matching from the start of the input to the first question mark or the end of input whichever comes first.
Something like this should work...
var pattern = /\/.*?(\?|$)/;
You don't really need a regex here, you could simply use indexOf() and substr():
var qPos = url.indexOf('?');
var path = (qPos === -1) ? url : url.substring(0, qPos);

Regex in javascript complex

string str contains somewhere within it http://www.example.com/ followed by 2 digits and 7 random characters (upper or lower case). One possibility is http://www.example.com/45kaFkeLd or http://www.example.com/64kAleoFr. So the only certain aspect is that it always starts with 2 digits.
I want to retrieve "64kAleoFr".
var url = str.match([regex here]);
The regex you’re looking for is /[0-9]{2}[a-zA-Z]{7}/.
var string = 'http://www.example.com/64kAleoFr',
match = (string.match(/[0-9]{2}[a-zA-Z]{7}/) || [''])[0];
console.log(match); // '64kAleoFr'
Note that on the second line, I use the good old .match() trick to make sure no TypeError is thrown when no match is found. Once this snippet has executed, match will either be the empty string ('') or the value you were after.
you could use
var url = str.match(/\d{2}.{7}$/)[0];
where:
\d{2} //two digits
.{7} //seven characters
$ //end of the string
if you don't know if it will be at the end you could use
var url = str.match(/\/\d{2}.{7}$/)[0].slice(1); //grab the "/" at the begining and slice it out
what about using split ?
alert("http://www.example.com/64kAleoFr".split("/")[3]);
var url = "http://www.example.com/",
re = new RegExp(url.replace(/\./g,"\\.") + "(\\d{2}[A-Za-z]{7})");
str = "This is a string with a url: http://www.example.com/45kaFkeLd in the middle.";
var code = str.match(re);
if (code != null) {
// we have a match
alert(code[1]); // "45kaFkeLd"
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
The url needs to be part of the regex if you want to avoid matching other strings of characters elsewhere in the input. The above assumes that the url should be configurable, so it constructs a regex from the url variable (noting that "." has special meaning in a regex so it needs to be escaped). The bit with the two numbers and seven letter is then in parentheses so it can be captured.
Demo: http://jsfiddle.net/nnnnnn/NzELc/
http://www\\.example\\.com/([0-9]{2}\\w{7}) this is your pattern. You'll get your 2 digits and 7 random characters in group 1.
If you notice your example strings, both strings have few digits and a random string after a slash (/) and if the pattern is fixed then i would rather suggest you to split your string with slash and get the last element of the array which was the result of the split function.
Here is how:
var string = "http://www.example.com/64kAleoFr"
ar = string.split("/");
ar[ar.length - 1];
Hope it helps

I want regular expression to get only numbers

I want a regular expression to get only numbers from a string.I want to ignore the number preceding with a character.
Example : "(a/(b1/8))*100
Here I dont want to fetch b1.I want to get only the numbers like 8,100 etc
You can use a word boundary, though that would not match after underscores:
\b\d+
(?<![a-zA-Z])\d+ should work
You can use a regular expression to find both numbers with and without a leading character, and only keep the ones without:
var str = "(a/(b1/8))*100";
var nums = [], s;
var re = /([a-z]?)(\d+)/g;
while (s = re.exec(str)) {
if (!s[1].length) nums.push(s[2]);
}
alert(nums);
Output:
8, 100
Demo: http://jsfiddle.net/Guffa/23BnQ/
for only number
^(\d ? \d* : (\-?\d+))\d*(\.?\d+:\d*) $
this will accept any numeric value include -1.4 , 1.3 , 100 , -100
i checked it for my custom numeric validation attribute in asp net

Categories