Javascript/Regex: Expression works in one environment and not another - javascript

I am trying to only allow alphanumeric entry or these characters:'()-_. (with the "." included)
Using regexpal.com I entered this regular expression: [^a-zA-Z0-9()\.'\-\_ ]
It is correctly identifying * and # as a match. What's baffling is that I have that same exact expression in my javascript on an .aspx page and it is not catching * or #. I have confirmed that is indeed entering that function and that the expression evaluates. Here is that code:
$(".validateText").keyup(function (e) {
var matchPattern = "[^a-zA-Z0-9()\.'\-\_ ]";
var regEx = new RegExp(matchPattern);
console.log("Regex: " + regEx + "\nValue of " + e.target.id + " is: " + e.target.value);
if (regEx.test(e.target.value)) {
console.log("Found invalid data.");//I don't get here with # or *
var failingChar = e.target.value.length - 1;
e.target.value = e.target.value.substring(0, failingChar);
}
});

Rather than using string literals to define regexes, use regex literals.
var regEx = /[^a-zA-Z0-9()\.'\-\_ ]/;
String literals interpret backslashes as escape characters, so they need to be escaped. Regex literals don't require this.
As per Bergi's suggestion, you wouldn't even need to escape all those characters.
/[^a-zA-Z0-9().'_ -]/
You could probably even use the general \w character.
/[^\w().' -]/

var matchPattern = "[^a-zA-Z0-9()\\.'\\-\\_ ]";
Would work.

Related

Replace matching elements in array using regular expressions: invalid character

var input = [paul, Paula, george];
var newReg = \paula?\i
for(var text in input) {
if (newReg.test(text) == true) {
input[input.indexOf(text)] = george
}
}
console.log(input)
I don't know what's wrong in my code. it should change paul and Paula to george but when I run it it says there's an illegal character
The backslash (\) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
So, thats what is causing your error, you need to replace \paula?\i with /paula?/i
You need to replace \ by / in your regexp pattern.
You should wrap the strings inside quotes "
You need to match correctly your array, val is just the index of the word, not the word himself.
var input = ["paul", "Paula", "george"];
var newReg = /paula?/i;
for (var val in input) {
if (newReg.test(input[val]) == true) {
input[input.indexOf(input[val])] = "george";
}
}
console.log(input);
JSFIDDLE

why is my regular expression not validating a valid expression?

I am at a lost as to why this will not.
here is my regular expression:
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\.\[\]_£|`¬':;~{}<>()#?!#$%^&*-]).{8,20}$
here is some code to simply test it:
var str1 = "AAbb123.";
var str2 = "ell";
var re = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\.\[\]_£|\`¬':\;\~{}<>()#?!\#$\%^&*-]).{8,20}$");
if(str1.match(re)){
alert("matched")
}
else {
alert("doesnt match")
}
the regular expression has been validated in 2 regular expression web sites (regexpal.com & http://www.freeformatter.com/regex-tester.html). both say str1 is valid for this expression but yet when included in my code it will not work.
below is another place I am trying to get the code working. and it keeps printing: requirements not met.
var uname = document.getElementById("pword1").value;
var re = new RegExp ("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\.\[\]_£|\`¬':\;\~{}<>()#?!\#$\%^&*-]).{8,20}$");
if(uname.match(re)){
DIMR = "Requirements MET";
}else {
DIMR = "Requirements NOT MET";
}
You need to properly escape a string when using new RegExp constructor.
Since you don't have any variables inside your pattern try
var str1 = "AAbb123.";
var str2 = "ell";
var re = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\+\=\.\[\]_£|\`¬':\;\~{}<>()#?!\#$\%^&*-]).{8,20}$/;
if(str1.match(re)){
alert("matched")
}
else {
alert("doesnt match")
}
Escaping only few characters present inside the character class would be enough. When using " as regex delimiter, you need to escape the backslash in your regex one more time.
var re = new RegExp("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[\\\\+=.\\[\\]_£|`¬':;~{}<>()#?!#$%^&*-]).{8,20}$");
special characters like +, ., * inside a character class would must match a literal + or . or *, so you don't need to escape it. To match a literal \, you need to escape that \ exactly three times.

How to detect namespace string in Javascript regular expression?

I need to check if a string represents a valid namespace format. A namespace is comprised of ids separated with dots. Each id starts with an alphabetic character and continues with an alphanumeric character.
Valid namespaces:
"com.company.package"
"com.company"
"com"
Invalid namespaces:
"1com.company.package"
"com.1company"
"com.com%any"
".com.company"
"com.company."
"com "
" com"
""
"."
"com..company"
Currently I use this simple regexp but it really don't check all of those invalid namespaces:
if( /^[\w\.]$/.test( namespaceStr ) ) {
//valid namespace
} else {
//invalid namespace
}
Any better suggestion for a small and efficient way to check if a string represents a valid namespace?
Here is a little jsfiddle that you can use for testing this regular expression: http://jsfiddle.net/bA85y/
Edit: This one should work for every case:
/^(?:[a-z]\d*(?:\.[a-z])?)+$/i
If you don't care about capturing groups even shorter:
/^([a-z]\d*(\.[a-z])?)+$/i
A little explanation:
^ // Start
( // Open group
[a-z]\d* // Must start by letter and may be followed by a number (greedy)
(\.[a-z])? // It may be followed by a dot only if it's followed by a letter (non-greedy)
)+ // Close group and match at least once so we get rid of empty values
$ // Ends, not allow any other characters
Demo: http://jsfiddle.net/elclanrs/5hnQV/
Try this pattern:
/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)*$/i
EDIT:
this is a reversion of #elclanrs jsfiddle
I think you are looking for this:
/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i
EDIT:
This one is a little better (with ?: and \d inspired by #HashemQolami and #elclanrs):
/^[a-z][a-z\d]*(?:\.[a-z][a-z\d]*)*$/i
And this one is shorter but does the same job:
/^[a-z](?:[a-z\d]*(?:\.[a-z])?)*$/i
And this one too, using lookahead to test that it doesn't end with a .:
/^(?!.*\.$)(?:[a-z][a-z\d]*\.?)+$/i
Please note that the selected answer doesn't work with "a.b.c" or in some cases with more than two levels.
UPDATE:
I've made a little (very basic) test:
var valid = [
"com.company.package",
"com.company",
"com.company1",
"com1.company1",
"a.b.c",
"a1.b.c3.d",
"a1.b2.c3.d4"];
var invalid = [
"1com.company.package",
"com.1company",
"com.com%any",
".com.company",
"com.company.",
"com ",
" com",
"",
".",
"com..company"];
function testRegex(regex, list)
{
var res=[];
for(var i=0; i<list.length; i++)
{
if(regex.test(list[i]))
res.push(list[i] + " ==> matched");
else
res.push(list[i] + " ==> NOT matched");
}
return res.join('<br>');
}
var regex = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/i;
var html = "<p>VALID</p>";
html += testRegex(regex, valid);
html += "<p>INVALID</p>";
html += testRegex(regex, invalid);
document.write("<div>" + html + "</div>");
Based on #dionyziz answer this work:
/^[a-z]+(\.[a-z]+)*[^.\s]$/
The following regular expression will do what you need. It checks for an alphabetic string and then allows multiple other alphabetic strings separated by a dot.
/^[a-z]+(\.[a-z]+)*$/

Regex Wildcard for Array Search

I have a json array that I currently search through by flipping a boolean flag:
for (var c=0; c<json.archives.length; c++) {
if ((json.archives[c].archive_num.toLowerCase().indexOf(query)>-1)){
inSearch = true;
} }
And I have been trying to create a wildcard regex search by using a special character '*' but I haven't been able to loop through the array with my wildcard.
So what I'm trying to accomplish is when query = '199*', replace the '*' with /[\w]/ and essentially search for 1990,1991,1992,1993,1994 + ... + 199a,199b, etc.
All my attempts turn literal and I end up searching '199/[\w]/'.
Any ideas on how to create a regex wildcard to search an array?
Thanks!
You should write something like this:
var query = '199*';
var queryPattern = query.replace(/\*/g, '\\w');
var queryRegex = new RegExp(queryPattern, 'i');
Next, to check each word:
if(json.archives[c].archive_num.match(queryRegex))
Notes:
Consider using ? instead of *, * usually stands for many letters, not one.
Note that we have to escape the backslash so it will create a valid string literal. The string '\w' is the same as the string w - the escape is ignored in this case.
You don't need delimiters (/.../) when creating a RegExp object from a string.
[\w] is the same as \w. Yeah, minor one.
You can avoid partial matching by using the pattern:
var queryPattern = '\\b' query.replace(/\*/g, '\\w') + '\\b';
Or, similarly:
var queryPattern = '^' query.replace(/\*/g, '\\w') + '$';
var qre = query.replace(/[^\w\s]/g, "\\$&") // escape special chars so they dont mess up the regex
.replace("\\*", "\\w"); // replace the now escaped * with '\w'
qre = new RegExp(qre, "i"); // create a regex object from the built string
if(json.archives[c].archive_num.match(qre)){
//...
}

Escape string for use in Javascript regex [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I am trying to build a javascript regex based on user input:
function FindString(input) {
var reg = new RegExp('' + input + '');
// [snip] perform search
}
But the regex will not work correctly when the user input contains a ? or * because they are interpreted as regex specials. In fact, if the user puts an unbalanced ( or [ in their string, the regex isn't even valid.
What is the javascript function to correctly escape all special characters for use in regex?
Short 'n Sweet (Updated 2021)
To escape the RegExp itself:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
To escape a replacement string:
function escapeReplacement(string) {
return string.replace(/\$/g, '$$$$');
}
Example
All escaped RegExp characters:
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
Find & replace a string:
var haystack = "I love $x!";
var needle = "$x";
var safeNeedle = escapeRegExp(needle); // "\\$x"
var replacement = "$100 bills"
var safeReplacement = escapeReplacement(replacement); // "$$100 bills"
haystack.replace(
new RegExp(safeNeedle, 'g'),
escapeReplacement(safeReplacement),
);
// "I love $100 bills!"
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!## ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
Test Case: A typical url
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
The Long Answer
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!##$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());

Categories