Placing variable in JavaScript regex - javascript

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';

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")

javascript syntax for regex using variable as pattern

I have a variable patt with a dynamic numerical value
var patt = "%"+number+":";
What is the regex syntax for using it in the test() method?
I have been using this format
var patt=/testing/g;
var found = patt.test(textinput);
TIA
Yeah, you pretty much had it. You just needed to pass your regex string into the RegExp constructor. You can then call its test() function.
var matcher = new RegExp("%" + number + ":", "g");
var found = matcher.test(textinput);
Hope that helps :)
You have to build the regex using a regex object, rather than the regex literal.
From your question, I'm not exactly sure what your matching criteria is, but if you want to match the number along with the '%' and ':' markers, you'd do something like the following:
var matcher = new RegExp("%" + num_to_match + ":", "g");
You can read up more here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
You're on the right track
var testVar = '%3:';
var num = 3;
var patt = '%' + num + ':';
var result = patt.match(testVar);
alert(result);
Example: http://jsfiddle.net/jasongennaro/ygfQ8/2/
You should not use number. Although it is not a reserved word, it is one of the predefined class/object names.
And your pattern is fine without turning it into a regex literal.
These days many people enjoy ES6 syntax with babel. If this is your case then there is an option without string concatenation:
const matcher = new RegExp(`%${num_to_match}:`, "g");

how to use a variable in RegExp with search method in 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.

How to use variables inside Regular Expression in Javascript

I want to build a RegEx in JavaScript that matches a word but not part of it. I think that something like \bword\b works well for this. My problem is that the word is not known in advance so I would like to assemble the regular expression using a variable holding the word to be matched something along the lines of:
r = "\b(" + word + ")\b";
reg = new RegExp(r, "g");
lexicon.replace(reg, "<span>$1</span>"
which I noticed, does not work. My idea is to replace specific words in a paragraph with a span tag. Can someone help me?
PS: I am using jQuery.
\ is an escape character in regular expressions and in strings.
Since you are assembling the regular expression from strings, you have to escape the \s in them.
r = "\\b(" + word + ")\\b";
should do the trick, although I haven't tested it.
You probably shouldn't use a global for r though (and probably not for reg either).
You're not escaping the backslash. So you should have:
r = "\\b(" + word + ")\\b"; //Note the double backslash
reg = new RegExp(r, "g");
Also, you should escape special characters in 'word', because you don't know if it can have regex special characters.
Hope this helps. Cheers
And don't write expressions in the regexp variable, because it does not work!
Example(not working):
var r = "^\\w{0,"+ maxLength-1 +"}$"; // causes error
var reg = new RegExp(r, "g");
Example, which returns the string as expected:
var m = maxLength - 1;
var r = "^\\w{0,"+ m +"}$";
var reg = new RegExp(r, "g");
Use this
r = "(\\\b" +word+ "\\\b)"

Categories

Resources