SyntaxError: unterminated parenthetical for validating the local file path - javascript

I have to validate the local folder path which is in the following format : ..\sentinel\log .
I have old regular expression ( /[\w]:\.*/)) for C:\sentinel\log and that was working. I need to make accept this path.
I have the following expresion from regexplibrary
var pathRE = new RegExp("/^((../|[a-zA-Z0-9_/-\])*.[a-zA-Z0-9])"); Error :
SyntaxError: unterminated parenthetical
When i executing is throw this error
I am attaching the code that i have tried
function checkFolderpath(path) {
try {
//var pathRE = new RegExp(/[\w]:\\.*/);
var pathRE = new RegExp("/^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9])");
if (pathRE.test(path)) {
$("#spanloggererror").html("");
return true;
}
else {
$("#spanloggererror").html(resx_Invalid_Loggerpath);
valtemp = 1;
}
return false;
}
catch (err) {
alert(err.Message);
}
Please suggest me how to fix the issue.
Edit :
value of path : ..\Sentinel\log

Your regular expression should be constructed like this:
var pathRE = /^((..\/|[a-zA-Z0-9_/-\\])*.[a-zA-Z0-9])/;
The only time you really need to use the RegExp constructor is when you're building up a regular expression from separate pieces, dynamically. You have to be careful with quoting forward-slash characters in the expression (/) when you use native regular expression syntax. You don't have to quote them inside [ ] groups, but you do need to double your backslashes.
That regular expression won't match ..\what\ever because it only looks for forward slash at the start. It also won't match a terminal file name longer than two characters. I think a better one would be:
var pathRE = /^\.\.(?:\\[A-Za-z0-9_-]+)+/;
with appropriate changes for the file name characters you expect.

Escape the slash:
/^((\.\./|[a-zA-Z0-9_\/\-\\])*\.[a-zA-Z0-9])/
// here __^ and add slash __^

Related

javascript, declare associative array of regex expressions

How to declare associative array of regex?
This is not working
var Validators = {
url : /^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm
};
EDITED: Now working!
This will be valid in JS (like # operator in C#)
url : `/^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm`
However, will still not work due to double escape, one in JS and other in Regex. If expression is small, perhaps naked eye can manually escape for both JS and Regex. My brain just can't :)
In order to use strings as tested on regex101.com for example, all required strings should be declared as 'row' like this:
var exp = String.raw`^(http(s?):\/\/)?(((www\.)?[a-zA-Z0-9\.\-\_]+(\.[a-zA-Z]{2,3})+)|(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b))(\/[a-zA-Z0-9\_\-\s\.\/\?\%\#\&\=]*)?$`;
var strings = [
String.raw`http://www.goo gle.com`,
String.raw`http://www.google.com`,
];
Wrap it with new RegExp() and escape slashes
var Validators = {
url : new RegExp( /^http(s?):\/\/((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(\/)?$/gm )
};
Your regex has forward slashes in it. This symbol needs to be escaped because it is supposed to indicate the start and end of the expression. Try \/.

Search for Literal String

I'm trying to find certain characters in a string and I receive the error "Unterminated string literal".
I'm searching for "\". Is there a way to find this character (or other literal strings) without an error?
thanks,
Here is the simple function:
function test() {
var a = "AGA_NAA1\MTH1.33";
var rep = a.replace("\","-");
Browser.msgBox(rep);
}
ERROR: Unterminated string literal.
I realize you are sharing a simplified example. However, this is happening because on variable a you also need double backslash because backslash is a special "escape" character:
function test() {
var a = "AGA_NAA1\\MTH1.33";
var rep = a.replace("\\","-");
Browser.msgBox(rep);
}

Regular Expression: Allow only characters a-z, A-Z

ExtJS 5.1
Let's say I have an example like that, I want user's name-surname so I don't want any numbers or special chars, I tried so many possibilities but couldn't make it:
var controller=this;
var refs = controller.getReferences();
var exp = '/^([^0-9]*)$/';
onButtonClick: function(button, e, eOpts) {
if(refs.nameSurname.value.match(exp)){
Ext.Msg.alert('ERROR', 'BlaBla');
}
}
With this code, I have no error when i enter a number to text field...
Thank you.
Assuming you need to actually match a string that has no digits...
You should not enclose the regex literal with single quotes, remove them. You do not need the capture group, you can remove ( and ).
Use
var exp = /^[^0-9]*$/;
Now, to check if a string matches a regex, you will be safer using a RegExp#test().
See the demo below:
var refs_nameSurname = "Som8ehere";
if(!(/^[^0-9]*$/.test(refs_nameSurname))){
console.log('ERROR');
}
However, you can reverse the logic, and show an error once a digit is found inside a string (simpler!):
var refs_nameSurname = "Somehere12";
if(/[0-9]/.test(refs_nameSurname)){
console.log('ERROR');
}

Nodejs regexp error: "Invalid regular expression: nothing to repeat"

So I have this regular expression:
(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#exclude[ \t]*([^\n*]*)[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?((?:.|\n|\r)*?)(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#endexclude[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?
Which is supposed to match anything that looks like this:
/* #exclude */
hurdur = somerandomtextorcode;
/* #endexclude */
I am trying this regular expression in tools such as https://regex101.com/ (https://regex101.com/r/eA5oK9/1) and there it just simply works, no errors.
However, in the nodejs environment, I get this error which I really do not know how to solve:
Warning: Invalid regular expression: /(?:[ ]*)?(?://|/*)[ ]*#exclude[
]*([^
]*)[ ]*(?:*/)?(?:[ ]*[
]+)?((?:.|
|
)?)(?:[ ]*)?(?://|/*)[ ]*#endexclude[ ]*(?:*/)?(?:[ ]*[
]+)?/: Nothing to repeat Use --force to continue.
Any help on this would be greatly appreciated!
Alright, it turns out it was a problem related to the way I was actually creating the regular expression.
I was creating (and applying) the regular expression like this:
var rExclude = '(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#exclude[ \t]*([^\n*]*)[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?((?:.|\n|\r)*?)(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#endexclude[ \t]*(?:\*\/)?(?:[ \t]*[\r\n]+)?';
contents = contents.replace(new RegExp(rExclude, 'gi'), function () { return ""; });
This gives me the error that is described in the starting post.
However, because the regular expression is in a string, JavaScript decides it wants to handle the regular expression differently. You can fix it in two ways:
Solution 1
This solution alters the way stuff is being escaped in your string.
var rExclude = '(?:[ \t]*)?(?://|/\\*)[ \t]*#exclude[ \t]*(?:\\*/)?(?:.|\n|\r)*?(?://|/\\*)[ \t]*#endexclude[ \t]*(?:\\*/)?';
contents = contents.replace(new RegExp(rExclude, 'gi'), function () { return ""; });
Solution 2
This solution alters the way the actual regular expression is being created:
contents = contents.replace(/(?:[ \t]*)?(?:\/\/|\/\*)[ \t]*#exclude[ \t]*(?:\*\/)?(?:.|\n|\r)*?(?:\/\/|\/\*)[ \t]*#endexclude[ \t]*(?:\*\/)?/gi, function () { return ""; });
It's just another weird ass JavaScript quirk, unfortunately.
Double-up your backslashes.
Notice how here: (?:*/)? there's no backslash? This means your * is trying to repeat.. nothing. Nothing to repeat.

regular expression not working when provided in double quotes in javascript

I am trying to use regular expession in javascript but it is not working. My custom control contains property called RegEx which is provided by user and I need to validate the input value against this regex. As properties in JS will be in double quotes("") the regualr expression fails(case -1). Case 2 succeeds thought both the cases regualr expression is same, the only difference is case- 1 it goes as double quotes. can somebody tell me why it is not working.
RegexExp="/^\d{5}$/"- at my aspx page
var value = "11111";
if(value.toString().search($(element).attr('RegexExp')) != -1)
{
return true;
}
else
{
return false;
}
var reg = /^\d{5}$/;
if(value.toString().search(reg) != -1)
{
return true;
}
else
{
return false;
}
Do this instead:
var reg = new RegExp($(element).attr('RegexExp'));
Update: you also need to strip the / characters, as these shouldn't be given to the RegExp constructor:
var regexExp = $(element).attr('RegexExp');
var reg = new RegExp(regexExp.substring(1, regexExp.length - 1));
I assume that the code that you posted is part of the function from the return statements, but if it is not, your first problem is that return is not allowed to be used out side of functions.
In any case, try the following. You can create a RegExp from a string by using its formal constructor
value.search(new RegExp($(element).attr('RegexExp')));
Also, you do not need to use toString() on value since it is already a string and your code is unnecessarily verbose. The following is equivalent to your first if else statement
return value.search(new RegExp($(element).attr('RegexExp'))) != -1;
Edit:
If you want to be able to pass in an expression as "/[expression]/" or "/[expression]/gi", you can do the following:
var toRegExp = function(regexString) {
var expression = regexString.substr(1), // remove first '/'
closingSlash = expression.lastIndexOf("/"); // find last '/'
return new RegExp(
// Expression: remove everything after last '/'
expression.substr(0, closingSlash),
// Flags: get everything after the last '/'
expression.substr(closingSlash+1)
);
}
....
value.search( toRegExp($(element).attr('RegexExp')) );
First, don't use a custom attribute to hold a regular expression. Second, "RegexExp" is redundant — that's like saying "regular expression expression". Third, to convert from a String to a RegExp, you have to wrap the string with new RegExp(); JavaScript is not weakly typed. That said, assuming that the regular expression isn't being set server-side, I'd recommend using jQuery's data API. It has the added advantage that it can store regular expression objects directly.
To set:
jQuery.data($(element).get(0), "regexp", /^\d{5}$/);
To get:
jQuery.data($(element).get(0), "regexp");
But ultimately, what you really want is the jQuery Validation plugin. It does everything you need and then some. Incidentally, it uses the data API internally to work its magic.
Documentation
The /.../ syntax is used to declare a regular expression object in Javascript, so you shouldn't use that to specify a regular expression pattern, it should be just regexp="^\d{5}$" as the attribute.
The search method takes a regular expression object as parameter, so you have to create a regular expression object from the string that you get from the attribute:
var reg = new RegExp($(element).attr('regexp'));
if (value.toString().search(reg) != -1) {
(You see the similarity with your second case?)
Or as a single expression:
if (value.toString().search(new RegExp($(element).attr('regexp'))) != -1) {

Categories

Resources