Is using var foo = new RegExp necessary? [duplicate] - javascript

This question already has answers here:
Are /regex/ Literals always RegExp Objects?
(3 answers)
Closed 10 years ago.
While researching the use of regular expressions in javascript, one can encounter examples of two types:
A:
var regex = /^[a-zA-Z0-9]+$/;
B:
var regex = new RegExp ("^[a-zA-Z0-9]*$");
Is it necessary to use var foo = new RegExp? Or, when should one pick each method?

The RegExp() constructor is useful when you have to assemble a regular expression dynamically at run time. If the expression is completely static, it's easier to use the native regex syntax (your "A"). The ease-of-use of the native syntax stems from the fact that you don't have to worry about quoting backslashes, as you do when your regular expression begins life as a string constant.

Is it necessary to use var foo = new RegExp?
No, obviously not. The other one works as well.
Or, when should one pick each method?
Regex literals are easier to read and write as you do not need to string-escape regex escape characters - you can just use them (backslashes, quotes). Also, they are parsed only once during script "compilation" - nothing needs to be executed each time you the line is evaluated.
The RegExp constructor only needs to be used if you want to build regexes dynamically.

Here's an example of a 'dynamic' regular expression where you might need new RegExp.
var search = 'dog',
re = new RegExp('.*' + search + '.*');
If it's a static regular expression, then the literal syntax (your A option) is better because it's easier to write and read.

Related

Why does in ASP.net Core MVC causes Javascript Error when I pass the string on my model? [duplicate]

Im trying to replace illegal characters from a filename using a regular expression in javascript but it keeps falling over in IE 11 with 'Syntax error in regular expression'. The same code works fine in Chrome and Edge.
String.prototype.replaceAll = function (search, replacement) {
var target = this;
return target.replace(search, replacement);
};
var filename = 'test+&+this+again.2016.txt';
filename = filename.replaceAll(new RegExp(/[^a-zA-Z0-9_\-&.]+/, 'g'), '_');
Desired output is
filename = 'test_&_this_again.2016.txt';
Any help would be greatly appreciated.
Thanks
The point is that RegExp constructor accepting the regex literal object is not supported in all browsers as you see. Use a common code like this:
filename = 'test+&+this+again.2016.txt';
filename = filename.replace(/[^a-zA-Z0-9_&.-]+/g, '_');
document.body.innerHTML = filename;
For it to work consistently. When the browsers start complying with the ES6, there won't be any trouble using the regex literal object inside the constructor (source: MDN):
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.
Also, I suggest using a regex literal notation since the pattern is not built dynamically. Here is the recommendation from MDN:
The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant...
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.
Double escape \\ and a string representation should do it:
filename = filename.replaceAll(new RegExp('[^a-zA-Z0-9_\\-&.]+', 'g'), '_');

Need help to use regex in match function of javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 5 years ago.
I am using a regex for getting some pattern data and it is working fine but I need to use some part of regex from a variable but I am unable to do that please help me if somebody know how to make it.
var subStr = document_root.documentElement.outerHTML.match(/http(.*?Frover.fff.com.*?)\;/g);
alert(subStr[0]);
I get first result in alert but need to do it like this.
var link=rover.fff.com;
var regexpattern="/http(.*?F"+link+".*?)\;/g"
var rex=new RegExp(regexpattern);
var subStr = document_root.documentElement.outerHTML.match(regexpattern);
alert(subStr[0]);
I don't get anything.
Please help me.
Comment if you confuse in anything.
In JavaScript, when you need to use a variable, you have to create a new RegExp object, as you've tried.
It takes two parameters. The first is a string of the pattern (without the slashes at the start and end). The second is any flags (like your g).
So, your pattern would be something like this:
var regexpattern = new RegExp('http(.*?F' + link + '.*?)\\;', 'g')
Note, that you have to escape any special characters in the string like you would any other string (in this case, your \ had to be escaped to \\ so it'll work properly).
After that, you use it the same as the /pattern/ form. In your case, be sure to use rex, not regexpattern in your match() function.
(If so some reason that wasn't a literal \ and you were escaping the semi-colon, just remove it completely, you won't need to escape a semi-colon.)

When does Javascript "initialize" a RegEx pattern?

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.

javascript string replace function [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I'm using the <string>.replace(/x/g,"y") to replace all instances of a character in a string to a different character, and I get exactly what I need.
My problem is with the syntax of the pattern (i.e. /x/g) that causes issues in a small post-processor I developed for all the javascript files included in my project.
The solution to my problem can be to encapsulate the string replacement within an isolated file that would not undergo post-processing.
(What post-processing does and why I use it is not important here)
My question: Suppose I create a function Switch_All_Chars(In_Str,Old_C,New_C) that replaces all instances of Old_C by New_C in In_str returning the updated string, and it would loo like:
function Switch_All_Chars(In_Str,Old_C,New_C) {
pat = /Old_C/g ;
return In_Str.replace( pat , New_C) ;
}
This would not work because par is not properly defined. Is there a syntax that would allow the definition of the pattern using a variable?
Thanks.
Use RegExp constructor:
var pat = new RegExp(Old_C, "g")

Can I avoid code duplication by referencing one Javascript Regexp literal inside another?

Is there a simple way to refer to one Javascript literal (e.g. "string") within another regexp literal?
Kind of familiar with Javascript Regexp but far from a guru. Trying to write a simple parser for a small handful of expression types. E.g. One type is expressions like:
`value gender 1='Male' 2 ='Female' 3="Didn't answer" >3 = 'Other';
Rather than write a whole parser in say, Jison, and the attendant learning curve, I thought it would be simple enough to use RegExp.
It appears Javascript Regexp can't capture an arbitrary number of repeating subgroups, and there's no clear character to split on, I'm parsing subgroups with their own regexps.
The following works okay, but the regexp literals are far from DRY, and all but unreadable. Each higher level construct repeats the lower level constructs.
var re_value_stmt = /value\s+(\w+)((?:\s+(?:[^=]+[=](?:(?:["][^"]+["])|(?:['][^']+[']))))+)/i
var re_value_clause = /([^=]+[=](\s*(?:(['][^']*['])|(["][^"]*["])))+)/ig
var re_value_elems = /([^=]+)[=]\s*(?:(?:[']([^']*)['])|(?:["]([^"]*)["]))/ig
console.log(re_value_elems.exec("1='Male'"));
console.log(re_value_clause.exec("1=\"Male\" 2=\"Female\""));
console.log(re_value_stmt.exec("value gender 1='Male' 2='Female'"));
For instance, (?:(?:["][^"]+["])|(?:['][^']+['])) just means QuotedString. Can I write that instead?
Is there a simple way to refer to one Javascript literal (e.g. "string") within another regexp literal? Specifying regexp by munging strings might work, but also seems awkward and error prone (e.g. needing to escape quote marks and escape escapes).
Or is this already the poster child for why people create parsers based on grammars and move out of Regexp?

Categories

Resources