This should be easy. I have the following code:
var patt = new RegExp("\d{3}[\-]\d{1}");
var res = patt.test(myelink_account_val);
if(!res){
alert("Inputs must begin with something like XXX-X of numbers and a dash!");
return;
}
Basically, forcing users to enter something like 101-4 . The code is borrowed from Social Security Number input validation . And I can confirm that my inputs are indeed like 101-4; only the first five characters need to fit the pattern.
But running my code always gives the alert--the condition is never matched.
Must be something simple?!
Thanks.
When you use "new RegExp" you are passing it a string.
Two solutions here:
1) Don't use "new RegExp()", but a regexp pattern:
var patt = /\d{3}[\-]\d{1}/
2) If you want to use it, remember you will have to escape the escapes:
var patt = new RegExp("\\d{3}[\\-]\\d{1}");
Also, remember, if a '-' is the only symbol (or first, or last) on a [], you can skip the escape:
var patt = new RegExp("\\d{3}[-]\\d{1}");
var patt = new RegExp("^\\d{3}[\\-]\\d{1}");
console.log(patt.test("123-4"));
console.log(patt.test("123-456"));
console.log(patt.test("12-4"));
console.log(patt.test("abc-d"));
Related
I have a small javascript funtcion :
function GetFilteredListLimited(event) {
var $source = $(event.target);
var $Pattern = event.data.Pattern;
var RE = new RegExp($Pattern, 'i');
if (RE.test($source.val())) {
console.log('RegEx match');
}
};
The pattern used is:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$
Which should match most email-addresses.
Using http://regexpal.com/ I can see that the Pattern is correct. But for some weird reason the script already matches at the 4th character after #
abc#abcd should not give a match, but is does.
Any suggestions ?
You need to be aware of RegExp constructor where escaped characters must be double-escaped. So, your regex string passed to the RegExp constructor should look like:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$
The fix can be introduced like this:
var RE = new RegExp($Pattern.replace(/\\/g, '\\\\'), 'i');
It will work if the escape symbols are used consistently.
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.
So what I want to match is anything that ends with ".ProjectName" so I wrote a small test case. I purposely created the pattern using RegExp because in the real case scenario I will be using a variable as part of the reg ex pattern. I'm not sure if my pattern is not correct (90% sure it correct), or if I am misusing the match function (70% sure I am suing it right). The blow code returns me something when the second case notMatchName should not return me anything
var inputName = "ProjectName";
var matchName = "userInput_Heading.Heading.ProjectName";
var notMatchName = "userInput_Heading.Heading.Date";
var reg = new RegExp(".*[." + inputName + "]");
console.log(reg);
console.log(matchName.match(reg));
console.log(matchName.match(reg)[0]);
console.log(notMatchName.match(reg));
console.log(notMatchName.match(reg)[0]);
Here is the JsFiddle to help.
Use
var reg = new RegExp(".*\." + inputName);
The square brackets mean: one character, which is one of those within the brackets. But you want several characzters, first a dot, then the first character of inputName, etc.
your regular expression should be .*\.projectName
if you rewrite your statement it will be
var reg = new RegExp(".*\." + inputName)
I'm using this RexExp code var userIdPattern = new RegExp('^([A-z0-9_.]{4,15})$');, I want to check if last character was dot (.) then .test() returns me false:
var userIdPattern = new RegExp('^([A-z0-9_.]{4,15})$');
console.log(userIdPattern.test('Omid.my.')); // -> I need this to be false
and in this case return me true:
userIdPattern.test('Omid.my'); //-> true
Following the update, a more appropriate regex might be:
var userIdPattern = new RegExp('^([A-Za-z0-9\[\]\\^`][A-z0-9_.]{2,13}[A-Za-z0-9\[\]\\^`])$');
That is, if you want to include other special characters in the usernames like 7stud mentioned in his comment and only exclude . and _ from the first and last characters.
Otherwise, to prevent those characters, I would suggest:
var userIdPattern = new RegExp('^([A-Za-z0-9][A-Za-z0-9_.]{2,13}[A-Za-z0-9])$');
Fiddle to test.
You can make it like this
^([A-z0-9_.]{3,14}[A-z0-9])$
Edit after reading your comment
^[a-z0-9][a-z0-9_.]{2,13}[a-z0-9]$
Preview
Also I suggest you use flag the i to ignore case:
var userIdPattern = new RegExp('^[a-z0-9][a-z0-9_.]{3,13}[a-z0-9]$', 'i');
I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")