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")
Related
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Match exact string
(3 answers)
Closed 5 years ago.
I have written the following function in javascript to validate a string that I will use as a file name. I would like to check for all the characters that are restricted by Windows OS as invalid while creating files. I checked the regular expression at RegExr, it seems to be working as expected but it doesn't work when called from an Angular controller and it only matches the first character in the parameter. I'm adding the file extension later on so that isn't a problem.
Can anybody help with it? I'm relatively new to regular expressions and would appreciate any help or pointers to useful resources.
function validateInput(value) {
if (!AngularUtils.isUndefinedOrNull(value)) {
var regex = new RegExp("[^<>/\\\\=|:*?\"]+$");
var regexOutput = regex.test(value);
if (!regex.test(value))
return true;
}
return false;
}
Edit:
Even after changing the regex to handle javascript constructors, I'm still getting valid matches for the following input: "sample_css", "sample=css","=sample"
Only the first string should be valid. jsfiddle here.
This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 7 years ago.
I have seen several similar questions on SO, but not exactly what I'm looking for.
I want to use a variable in my regEx so that when I call it, I can easily pass in a number.
Here's the hard coded regEx:
'mywonderfullString'.match(/.{1,3}/g)
Here's what I need:
'mywonderfullString'.match(/.{1,variableHERE}/g)
So when I call the regEx, I would do something like
'mywonderfullString'.match(/.{1,3}/g)
I've seen some examples using the replace regEx, but I can't seem to my example working.
You need to use RegExp constructor in-order to include variables inside regex.
var variableHERE = '3'
alert('mywonderfullString'.match(new RegExp(".{1," + variableHERE + "}", "g")))
This question already has answers here:
Javascript equivalent of Perl's \Q ... \E or quotemeta()
(3 answers)
Closed 2 years ago.
In Perl, there's a function named quotemeta which accepts a string and returns a regex pattern that matches that string. It's used in virtually every program to avoid code injection bugs.
One would use quotemeta when dynamically building a pattern. For example,
"^"+quotemeta(var)+"_\\d+$"
A JavaScript implementation follows:
function quotemeta(s) {
return String(s).replace(/\W/g, "\\$&");
}
Given how needed this function when working with regex patterns, I would have expected JavaScript to provide one. Does JavaScript or jQuery already have such a function?
JavaScript doesn't have such a method natively. (And jQuery doesn't include one)
Usually, when searching for a string pattenr, you'd use String.prototype.indexOf. This method find a string in a string, so you won't even need to convert the string pattern to a regex.
String.prototype.replace can also take a String pattern.
It is not exactly the same but it'll work for most string matching use cases.
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.
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I'm trying to convert following expression to "new Regexp()" style:
http://jsfiddle.net/HDWBZ/
var Wyrazenie = /\btest[a-z]*/g;
I'm really confused with it and have no idea how to fix it. Below is what I've done but obviously it doesn't work.
var Wyraznie = new RegExp("\btest[a-z]*","g");
Also have a question how would it look if instead of "test" I would use variable?
You should use this instead...
new RegExp("\\btest[a-z]*", "g");
... as \b will be interpolated into a single (slashless) character when JavaScript parser works through the corresponding string literal. The solution is to escape slash itself.
DEMO: http://jsfiddle.net/HDWBZ/1/