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.
Related
I'm new to Regex and I'm trying to work it into one of my new projects to see if I can learn it and add it to my repitoire of skills. However, I'm hitting a roadblock here.
I'm trying to see if the user's input has illegal characters in it by using the .search function as so:
if (name.search("[\[\]\?\*\+\|\{\}\\\(\)\#\.\n\r]") != -1) {
...
}
However, when I try to execute the function this line is contained it, it throws the following error for that specific line:
Uncaught SyntaxError: Invalid regular expression: /[[]?*+|{}\()#.
]/: Nothing to repeat
I can't for the life of me see what's wrong with my code. Can anyone point me in the right direction?
You need to double the backslashes used to escape the regular expression special characters. However, as #Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:
The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:
"[\\[\\]?*+|{}\\\\()#.\n\r]"
Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to #Bohemian's string, and works correctly.
Building off of #Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:
if (name.search(/[\[\]?*+|{}\\()#.\n\r]/) != -1) {
// ... stuff ...
}
Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).
For Google travelers: this stupidly unhelpful error message is also presented when you make a typo and double up the + regex operator:
Okay:
\w+
Not okay:
\w++
Firstly, in a character class [...] most characters don't need escaping - they are just literals.
So, your regex should be:
"[\[\]?*+|{}\\()#.\n\r]"
This compiles for me.
Well, in my case I had to test a Phone Number with the help of regex, and I was getting the same error,
Invalid regular expression: /+923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/: Nothing to repeat'
So, what was the error in my case was that + operator after the / in the start of the regex. So enclosing the + operator with square brackets [+], and again sending the request, worked like a charm.
Following will work:
/[+]923[0-9]{2}-(?!1234567)(?!1111111)(?!7654321)[0-9]{7}/
This answer may be helpful for those, who got the same type of error, but their chances of getting the error from this point of view, as mine! Cheers :)
for example I faced this in express node.js when trying to create route for paths not starting with /internal
app.get(`\/(?!internal).*`, (req, res)=>{
and after long trying it just worked when passing it as a RegExp Object using new RegExp()
app.get(new RegExp("\/(?!internal).*"), (req, res)=>{
this may help if you are getting this common issue in routing
This can also happen if you begin a regex with ?.
? may function as a quantifier -- so ? may expect something else to come before it, thus the "nothing to repeat" error. Nothing preceded it in the regex string so it didn't get to quantify anything; there was nothing to repeat / nothing to quantify.
? also has another role -- if the ? is preceded by ( it may indicate the beginning of a lookaround assertion or some other special construct. See example below.
If one forgets to write the () parentheses around the following lookbehind assertion ?<=x, this will cause the OP's error:
Incorrect: const xThenFive = /?<=x5/;
Correct:
const xThenFive = /(?<=x)5/;
This /(?<=x)5/ is a positive lookbehind: we're looking for a 5 that is preceded by an x e.g. it would match the 5 in x563 but not the 5 in x652.
I take care to declare a RegEx pattern once and reuse if possible, for performance reasons. I'm not entirely certain why - something I probably read once many years ago and has been filed away in the ol' skull sponge.
I find myself in a regex-heavy situation, and a thought occurred... does declaring a RegEx pattern "instantiate" or "initialize" that pattern, or does it just store the pattern until it's needed?
var NonNumbers = /[^0-9]/g; //"initialized" here?
"h5u4i15h1iu".replace(NonNumbers, "*"); //or "initialized" here?
Maybe RegExp() actually creates one and the literal waits until it's used, even though both patterns return the same results?
var NonNumbers = /[^0-9]/g; //just stores the pattern
var NonNumbers = RegExp(/[^0-9]/, 'g'); //actually creates the RegExp
Just an itch I'm hoping someone who understands the inner workings can scratch.
From the Mozilla spec:
You construct a regular expression in one of two ways:
Using a regular expression literal, which consists of a pattern enclosed between slashes, as follows:
var re = /ab+c/;
Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.
Or calling the constructor function of the RegExp object, as follows:
var re = new RegExp('ab+c');
Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.
Since the spec indicates that the regular expression is being compiled when using the literal syntax, it is also safe to assume that it is being initialized as a full, bona-fide regular expression object at that point.
Another advantage of using literals is that regular expressions can be interned, meaning that if the same regular expression literal is found in multiple places, both literals can refer to the same object, saving both memory and initialization costs.
Consider the following code:
`abc`.split(`b`)
`abc`.split(`b`)
This fails with TypeError: "abc".split(...) is not a function
Try it here.
To make it work, we need to insert a semicolon between those two statements.
Also the code works fine if we use a regular string on the second line:
`abc`.split(`b`)
"abc".split(`b`)
What is the reason for this behaviour?
I guess it has something to do with the automatic semicolon insertion doing some whacky stuff, but I can't figure out what this would be.
Also the fact that there seems to be a difference between regular and template strings kinda confuses me. Shouldn't those be equivalent?
Template literals can be tagged with a function, string literals cannot. Notice that
tag`a ${x} b`;
is basically equivalent to
tag("a ", x, " b");
Since your expression `abc`.split(`b`) `abc`.split(`b`) is grammatically valid, there is no automatic semicolon insertion happening here. Don't omit the semicolons where they are necessary. It's not that ASI is doing whacky stuff, it's just doing nothing while you expect it to.
If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with (, [, /, +, - or `.
I'm trying to find out if a string contains css code with this expression:
var pattern = new RegExp('\s(?[a-zA-Z-]+)\s[:]{1}\s*(?[a-zA-Z0-9\s.#]+)[;]{1}');
But I get "invalid regular expression" error on the line above...
What's wrong with it?
found the regex here: http://www.catswhocode.com/blog/10-regular-expressions-for-efficient-web-development
It's for PHP but it should work in javascript too, right?
What are the ? at the start of the two [a-zA-z-] blocks for? They look wrong to me.
The ? is unfortunately somewhat overload in regexp syntax, it can have three different meanings that I know of, and none of them match what I see in your example.
Also, your \s sequences need the backslash escaping because this is a string - they should look like \\s. To avoid escaping, just use the /.../ syntax instead of new Regexp("...").
That said, even that is insufficient - the regexp still produces an Invalid Group error in Chrome, probably related to the {1} sequences.
The ?'s are messing it up. I'm not sure what they are for.
/\s[a-zA-Z\-]+\s*:\s*[a-zA-Z0-9\s.#]+;/
worked for me (as far as compiling. I didn't test to see if it properly detected a CSS string).
Replace the quotes with / (slashes):
var pattern = /\s([a-zA-Z-]+)\s[:]{1}\s*([a-zA-Z0-9\s.#]+)[;]{1}/;
You also don't need the new RegExp() part either, which is why it's been removed; instead of using a quote or double quote to denote a string, JavaScript uses a slash / to denote a regular expression, which isn't a normal string.
That regular expression is very bad and I would avoid its source in the future. That said, I cleaned it up a bit and got the following result:
var pattern = /\s(?:[a-zA-Z-]+)\s*:\s*(?:[^;\n\r]+);/;
this matches something that looks like css, for example:
background-color: red;
Here's the fiddle to prove it, though I'd recommend to find a different solution to your problem. This is a very simple regex and it's not save to say that it is reliable.
I found this in a message forum, I don't know regex so I was hoping you could explain it to me or give me a better solution.
StrippedPrefix_JS_ItemNo = StrippedPrefix_JS_ItemNo.replace(/,$/,'');
What is the opening / for?
$ is end of line, I know that much, and I can see the empty replace ''.
/,$/
the /expression goes here/ is how javascript can define a regular expression. Without the /:
var expression = ,$;
That's a syntax error. So the slashes mark it as an expression. It can also be written, var expression = new RegExp(",$");.
More Info about JavaScript RegExp