Error to test a string with regex [duplicate] - javascript

This question already has an answer here:
regular expression for [allchars]
(1 answer)
Closed 7 years ago.
I want to find an occurrence of a word in a long string. This word changes with every iteration of the for loop:
array_word = '....'
for(var i.........) {
var regex=new RegExp('/.*'+array_word[i]+'.*/');
if(regex.test(array_word[i]) {
return true;
}
}
The problem could be that I used the wrong regex because the program doesn't return true, can anyone help me?

You don't need to use forward slashes.
var regex = new RegExp('.*'+array_word[i]+'.*');
.* won't be needed for this case.
var regex = new RegExp(array_word[i]);
From the docs,
There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:
/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');
The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

Related

Not able to escape "?" but "\" works fine in javascript regex

I have following example (in node):
var reg = new RegExp("aa\?b", 'g');
var msgg = "aa?b"
if(msgg.match(reg)){
console.log(1);
} else {
console.log(0);
}
This prints 0 or returns null. I don't understand why it works if ? is replaced with \ but not in case of ?.
Is ? some more special than any others??
You need to double escape, like this:
var reg = new RegExp("aa\\?b", 'g');
Or use RegExp literal:
var reg = /aa\?b/g;
Reason is that JavaScript string "\?" evaluates to "?" because ? is not a special escape character. Hence your RegExp receives a literal question mark and not an escaped one. Double escaping ensures the "\" is treated literally.
Passing the literal notation instead of the string notation to the constructor your regexp works:
var reg = new RegExp(/aa\?b/, 'g');
var msgg = "aa?b"
console.log(msgg.match(reg))
From MDN:
There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:
/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');
The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.
The constructor of the regular expression object, for example, new RegExp('ab+c'), 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.
Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a TypeError ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.
When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:
var re = /\w+/;
var re = new RegExp('\\w+');

How to match with new RegExp exactly [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 5 years ago.
I have this string:
var str = "https://www.mysite.se/this-match?ba=11"
I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:
var myre = new RegExp('\/this-ma\?');
Still matches:
myre.exec(str)[0]
"/this-ma"
How can I avoid that a shorter string contained in this-match does give a match?
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.
var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/
The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.
var myre = /\/this-ma\?/

Backslash Discrepancy between Regex Constructor and Literals [duplicate]

This question already has an answer here:
javascript why double escape dot/character [closed]
(1 answer)
Closed 7 years ago.
The title sums it up. I came across an odd discrepancy in backslash escaping between regular expression literals and constructor functions with new RegExp(), and I was curious about what's behind it.
I was trying to escape a parenthesis ( inside a constructor, like so:
var search = new RegExp('/(', 'g');
var result = "(test)".match(search);
But this kept returning an error. The match worked fine inside a literal /\(/g;, but inside the constructor I ended up having to do something like this:
search = new RegExp('\\(', 'g');
Can someone please explain to me why an escaping backslash requires an escaping backslash itself in a constructor, but not a literal?
Because the backslash is a special character in both the context of a regexp, and the context of a string literal. You have to get past the string literal's special usage before the regexp parser can see it and apply its own special rules.
NOTE If pattern is a StringLiteral, the usual escape sequence substitutions are performed before the String is processed by RegExp. If pattern must contain an escape sequence to be recognised by RegExp, any backslash \ characters must be escaped within the StringLiteral to prevent them being removed when the contents of the StringLiteral are formed.
http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.4.1

How do I include an inline comment in a regular expression in JavaScript [duplicate]

This question already has answers here:
Commenting Regular Expressions
(7 answers)
Closed 3 years ago.
Inline comments works when a string passed to the RegExp constructor:
RegExp("foo"/*bar*/).test("foo")
but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?
Javascript supports neither the x modifier, nor inline comments (?#comment). See here.
I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):
RegExp(
"foo" + // match a foo
"bar" + // followed by a bar
"$" // at the end of the string
).test("somefoobar");
Other than using a zero-length sub-expression, it's not possible. Examples of "comments":
/[a-z](?!<-- Any letter)/
(?!..) is a negated look-ahead. It matches if the previous is not followed by the string within the parentheses. Since the thing between (?! and ) is a real regular (sub)expression, you cannot use arbitrary characters unless escaped with a backslash
An alternative is to use the positive look-ahead:
/[a-z](?=|<-- Any letter)/
This look-ahead will always match, because obviously the a-z is also followed by an empty string.

Javascript RegEx Not Working [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 2 years ago.
I have the following javascript code:
function checkLegalYear() {
var val = "02/2010";
if (val != '') {
var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");
if (regEx.test(val)) {
//do something
}
else {
//do something
}
}
}
However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.
Because you're creating your regular expression from a string, you have to double-up your backslashes:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");
When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like
"^(0[1-9]|1[0-2])/\d{4}$"
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
Note that \d is now just d.
By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.
There's really no reason here not to use regular expression syntax instead:
var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;
edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.

Categories

Resources