javascript syntax for regex using variable as pattern - javascript

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

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

Regex or lastIndexOf when removing last instance of a string

I couldn't apply answers to other similar questions (trying to replace the last occurrence of a string) because I am having trouble with the syntax.
I'm trying to replace the last occurrence of a string. The value of the string is stored in a variable that is passed to the .replace() method like this:
var str += some additive strings;
var del = a string that lives within str; // the value is dynamic
str = str.replace(del$, ''); // this doesn't work to remove the last occurrence of `del` in str
As I understand it the $ argument looks for the last occurrence of a string within a regex; but I can't figure out how to use it alongside a variable passed to .replace(). Any suggestions?
If you want to use the RegExp with a $, do it like this:
var str += 'some additive strings';
var re = new RegExp('a string that lives within str$');
str = str.replace(re, '');
str = str.substring(0, str.length - del.length);
You can use lastIndexOf() with slice()
Example:
var str ="HI this is cool isn't it? cool";
var del='cool';// put whatever here
var index = test.lastIndexOf(del);
var length=del.length;
if(index!=-1)
var removeStr=test.substr(index,length);
str.replace(removeStr,''); // HI this is cool isn't it?
Mate, this is just an answer. You'll need to use it according to your needs.
Updated Live demo:http://jsfiddle.net/n2Kgn/2

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.

Categories

Resources