0

I am trying to understand why writing regex as a string is not working but using it without string does work.

this is my example:

var patt = new RegExp("/test_.*/gi");
var res = patt.test("test_4");
console.log(res);

will return false

but this:

var patt = /test_.*/gi;
var res = patt.test("test_4");
console.log(res);

will return true

what is the difference

2
  • see constructor call : docs Commented Jul 27, 2015 at 9:30
  • Although not related to the problem here (since it hasn't manifested), don't use g flag with test Commented Jul 27, 2015 at 9:30

4 Answers 4

2

Your syntax of RegExp is wrong.

  1. The delimiters are not required when you use RegExp constructor to create new Regular Expression.
  2. The flags should be passed as second parameter to the RegExp constructor.
  3. And . should to be escaped, if you want to match . literal.

Usage

var patt = new RegExp("test_.*", "gi");

Demo

var patt = new RegExp("test_.*", "gi");
var res = patt.test("test_4");
document.write(res);

Sign up to request clarification or add additional context in comments.

5 Comments

@lobengula3rd Check updated answer. I've also included Demo
why escape the . ? not the same Regex as OP.
Do not write "\." in string. While it technically works, since the \. resolves into . in the string literal before going into RegExp constructor, it is confusing to the reader
@Hacketo I thought OP wants to match . literal, Thanks for clarification, I've updated answer
@nhahtdh Thanks! I've updated answer
1

The regexp constructor does not need delimiters, also, flags are isolated in another argument which simplifies it to

var patt = new RegExp('test_.*', 'gi');
var res = patt.test("test_4");
console.log(res);

Comments

0

You do not need to include the / at the start and end of the regular expression when using the constructor and the flags need to be in the second argument. See the MDN Documentation for RegExp.

var patt = new RegExp( "test_.*", "gi" );
var res = patt.test("test_4");
console.log(res);

Comments

0

You are not calling the constructor correctly, the falgs should be passed as a second parameter:

new RegExp('test_.*', 'gi');

As you can see in Documentation, it should respect this format:

new RegExp(pattern[, flags])

This is your demo:

var patt = new RegExp("test_.*", 'gi');
var res = patt.test("test_4");
alert(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.