how to use a variable in RegExp with search method in Javascript? - javascript

I have a string:
var _codes = "1234,1414,5555,3333,2222,5566,4545";
var regex = new RegExp(/1234/i);
var _found = _codes.search(regex);
//this works sofar.
nowi want to do it with variable:
like this:
var id = "1234";
regex = new RegExp("\\"+id+"\\/i");
but it doesn't work. any ideas?
Thanks!

When using the RegExp constructor, you don't supply delimiters and the flags go in the second argument.
var id = "1234";
regex = new RegExp(id, "i");
However, the RegExp just for 1234 with i doesn't really make sense. Use indexOf() instead.
However, perhaps you really did mean to match numbers surrounded with a \. In that case, leave them in there.

Related

How can you add e.g. 'gm' to a regex to avoid repeating the full regex again? [duplicate]

I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")

Unable to convert a string to the desired regexp in Javascript [duplicate]

I am trying to create something similar to this:
var regexp_loc = /e/i;
except I want the regexp to be dependent on a string, so I tried to use new RegExp but I couldn't get what i wanted.
Basically I want the e in the above regexp to be a string variable but I fail with the syntax.
I tried something like this:
var keyword = "something";
var test_regexp = new RegExp("/" + keyword + "/i");
Basically I want to search for a sub string in a larger string then replace the string with some other string, case insensitive.
regards,
alexander
You need to pass the second parameter:
var r = new RegExp(keyword, "i");
You will also need to escape any special characters in the string to prevent regex injection attacks.
You should also remember to watch out for escape characters within a string...
For example if you wished to detect for a single number \d{1} and you did this...
var pattern = "\d{1}";
var re = new RegExp(pattern);
re.exec("1"); // fail! :(
that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...
var pattern = "\\d{1}" // <-- spot the extra '\'
var re = new RegExp(pattern);
re.exec("1"); // success! :D
When using the RegExp constructor, you don't need the slashes like you do when using a regexp literal. So:
new RegExp(keyword, "i");
Note that you pass in the flags in the second parameter. See here for more info.
Want to share an example here:
I want to replace a string like: hi[var1][var2] to hi[newVar][var2].
and var1 are dynamic generated in the page.
so I had to use:
var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
mystring.replace(regex,'[newVar]');
This works pretty good to me. in case anyone need this like me.
The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.
var keyword = "something";
var test_regexp = new RegExp(something,"i");
You need to convert RegExp, you actually can create a simple function to do it for you:
function toReg(str) {
if(!str || typeof str !== "string") {
return;
}
return new RegExp(str, "i");
}
and call it like:
toReg("something")

Placing variable in JavaScript regex

I've got a regular expression like this one:
var reg = /http:\/\/s(\d+)\.de\.example\.com\/(.*?)\.php(.*)/i;
I want to have a variable, exactly this: ccode[i][2] in place of .de.
How do I do that? Thank for your help.
You need to use a RegExp constructor notation if you want to use variables in your regex pattern, and inside it, you need to double escape special regex metacharacters. I.e.
var reg = new RegExp("http://s(\\d+)\\." + ccode[i][2] + "\\.example\\.com/(.*?)\\.php(.*)", "i");
From MDN:
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.
Sample code:
var ccode = "de";
var reg = new RegExp("http://s(\\d+)\\." + ccode + "\\.example\\.com/(.*?)\\.php(.*)", "i");
alert(reg.test("http://s123.de.example.com/something.php?some=params"));
Try this
var reg = '/http:\/\/s(\d+)\\'+ccode[i][2]+'\.example\.com\/(.*?)\.php(.*)/i';

How to use variable in regex

I have following RegExp and it is working fine
var reg = new RegExp(/(.{1,4})/g);
But now i want to replace 4 with variable called limit then it is not working
var reg = new RegExp("/(.{1,"+ limit +"})/g");
How could i use variable instead of fixed value in above RegExp?
Drop the /. RegExp expects a string or a regex. Then it takes a second parameter where you can specify the flags.
var reg = new RegExp("(.{1,"+ limit +"})", "g");
More here https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
Like this (you don't need the /):
var reg = new RegExp(".{1,"+ limit +"}", "g");
Use it like this,
var reg = new RegExp("(.{1,"+ limit +"}", "g");
The second parameter is used for options. And the pattern does not take any delimiter.

Javascript regular expression - string to RegEx object

I am sure its something pretty small that I am missing but I haven't been able to figure it out.
I have a JavaScript variable with the regex pattern in it but I cant seem to be able to make it work with the RegEx class
the following always evaluates to false:
var value = "someone#something.com";
var pattern = "^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);
but if I change it into a proper regex expression (by removing the quotes and adding the / at the start and end of the pattern), it starts working:
var value = "someone#something.com";
var pattern = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/
var re = new RegExp(pattern);
re.test(value);
since I always get the pattern as a string in a variable, I haven't been able to figure out what I am missing here.
Backslashes are special characters in strings that need to be escaped with another backslash:
var value = "someone#something.com";
var pattern = "^\\w+#[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
var re = new RegExp(pattern);
re.test(value);

Categories

Resources