I have added jQuery validator add method for the presence of http check in url field.
JS
jQuery.validator.addMethod("valid_url", function(value, element) {
if(!/^(https?|ftp):\/\/i.test(val))
val = 'http://'+val; // set both the value
$(elem).val(val); // also update the form element
}
My Console throws
"unterminated regular expression literal" error in the following line.
if(!/^(https?|ftp):\/\/i.test(val))
What my mistake is?
Regular expression literals should be surrounded by the delimiters(/). There's no terminating delimiter:
/^(https?|ftp):\/\//i
// ^
For example:
>> /^(https?|ftp):\/\//i.test('http://stackoverflow.com/')
true
>> /^(https?|ftp):\/\//i.test('telnet://stackoverflow.com/')
false
You can also get this error if you're simply attempting to concatenate a variable that utilizes a regular expression and forget a quotation mark somewhere.
Related
I used jquery validator for validation.I have 50 free emails like(gmail.com, yahoo.com) so I need validate it.I chose an array then stored all the emails within an array.Below see my code there you could see I used the regular expression.I passed a variable in regular expression but it doesn't work for me.It threw the error like this SyntaxError: invalid range in character class
My code
$.validator.addMethod('nofreeemail', function (value) {
var emails = ["gmail.com","yahoo.com","hotmail.com"]
$.each(emails,function(i, val){
console.log("email", val)
var regex = new RegExp("/^([\w-.]+#(?!"+val+")([\w-]+.)+[\w-]{2,4})?$/");
console.log("regex", regex)
return regex.test(value);
});
}, 'Free email addresses are not allowed.');
I will post an answer since it is not evident here what is going on, but the underlying reasons are quite common.
You are using a constructor notation to define the regex. It is a correct approach when you need to build a pattern dynamically using a variable. However, a literal backslash must be written as "\\". All single backslashes are removed. Thus, you get an error since [\w-.] turns into [w-.] and it is an invalid character class. Also, the regex delimiters (those /..../ around the pattern) should never be used in the constructor notation unless you really need to match a string enclosed with /.
Besides, your emails contain non-word chars, and you need to escape them.
Use
var regex = new RegExp("^([\\w-.]+#(?!"+val.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&')+")([\\w-]+\\.)+[\\w-]{2,4})?$");
I also believe the dot in ([\w-]+.)+ must be escaped, it is supposed to match a literal dot,
I can't minify a javascript file containing this working Regex:
isValid = function (str) {
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
},
Error message:
/* Minification failed. Returning unminified contents.
(2128,43-44): run-time error JS1004: Expected ';': {
(2128,45-46): run-time error JS1195: Expected expression: |
(2128,46-47): run-time error JS1014: Invalid character: \
(2128,47-48): run-time error JS1014: Invalid character: \
(2128,48-70): run-time error JS1015: Unterminated string constant:
":<>\?]/g.test(str);
(2129,6-7) : run-time error JS1195: Expected expression: ,
(2128,17-43): run-time error JS5017: Syntax error in regular expression:
/[~`!#$%\^&*+=\-\[\]\\';,/
*/
Bundle Config:
bundles.Add(new ScriptBundle("~/bundlesJs/custom").Include(
"~/Scripts/Autogenerated/AntiHacking/antiHackingHelper.js"
));
BundleTable.EnableOptimizations = true;
How can this be solved? Is there a character that needs to be escaped or should I wrap the whole Regex?
Acc. to ES5 docs, the forward slash is NOT a special regex metacharacter.
JavaScript regex engine always allows an unescaped / in a RegExp constructor notation and you may use an unescaped / forward slash inside character classes even when written in a regex literal notation, try this code (in Chrome, FF, and I have checked it in IE 11, too):
console.log( '1//25///6'.match(/\w[/]+\w/g) );
console.log( '1//25///6'.match(RegExp("\\w/+\\w", "g")) );
However, the best practice is to escape the regex delimiters to avoid any issues like the one you have and keep the patterns consistent and unambiguous.
I have a user-created string which is to be used as a regular expression. How can I test the validity of this string?
My first thought was to use a regular expression to test this, but, thinking about it, the regular expression syntax itself is not a regular language, so this doesn't work.
My second thought was to attempt to create a RegExp object using the string. However, the documentation does not mention what should happen when the string is an invalid regular expression.
Any other ideas?
Use try/catch to determine whether given string is able to create a valid RegExp object or not:
s = "(abc"; // invalid input regex string
valid = false;
try {
new RegExp(s);
valid = true; // reached here regex is valid
} catch(ex) {}
console.log(valid); // false
I need to remove trailing crlf from a string in jmeter. I have used the following function
${__javaScript('${varu_2}'.replace(/[\\r\\n]/g\,""))}
It gives me error "org.mozilla.javascript.EvaluatorException:
unterminated string literal (#1)".
Any help would be appreciated.
The inline evaluation (${varu_2}) of your variable containing multiple lines is broking the javascript evaluation.
For example the javascript would be interpreted as :
'line1
line2'.replace(/[\\r\\n]/g\,"")
The first line is an unterminated string like the error message tells us.
To avoid this behavior I would recommend using the JMeterVariables object, but since the javascript implementation (Rhino) does not seems to support well inline regexp, you should use 2 replace function instead of your regular expression:
${__javaScript(vars.get('varu_2').replace( "\r"\, "" ).replace("\n"\,""))}
Or if you prefer, with a beanshell function you can use any regular expression you :
${__BeanShell(vars.get("varu_2").replaceAll("[\r\n]"\,""))}
I have this line in my Javascript code:
var regex = /===Hello===\n/;
JsHint gives me a warning in this line:
A regular expression literal can be confused with '/='`
...but I don't know what's wrong with this regular expression? How can I avoid this warning?
The problem is that /= could be interpreted as a division and assignment, rather than the start of a regular expression literal.
You can avoid the warning by using the RegExp constructor instead:
var regex = new RegExp("===Hello===\n");
There doesn't appear to be any option you can set to tell JSHint (or JSLint for that matter) to ignore /=, so your choice is either to work around it or ignore the warning.