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")
Related
Need help getting the following JavaScript RegEx case insensitive:
^(ABCDE)\d{5}$
I have tried /i but it doesn't work:
^(ABCDE)\d{5}$/i
Where should I place /i to get it to work?
Thanks in advance.
When you have a literal regex notation, just use /.../:
var re = /^(ABCDE)\d{5}$/i;
If you use a RegExp constructor:
var re = RegExp("^(ABCDE)[0-9]{5}$", "i");
However, the literal notation is preferable here since the pattern is constant, known from the beginning, and no variables are used to build it dynamically. Note that if you were to use \d in the RegExp constructor, you'd have to double the backslashes:
var re = RegExp("^(ABCDE)\\d{5}$", "i");
Try to write it this way :
var regex = /^(ABCDE)\d{5}$/i;
It needs the first / or you can also use
var regex = new RegExp('^(ABCDE)\\d{5}$', 'i');
Then if you try in a console this it should work (online testers can add other issue, just try directly on your code) :
regex.test('ABCDE12345') // true
regex.test('abcde12345') // true
Test on Regex101 : https://regex101.com/r/zR5yR0/1
I have a small javascript funtcion :
function GetFilteredListLimited(event) {
var $source = $(event.target);
var $Pattern = event.data.Pattern;
var RE = new RegExp($Pattern, 'i');
if (RE.test($source.val())) {
console.log('RegEx match');
}
};
The pattern used is:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$
Which should match most email-addresses.
Using http://regexpal.com/ I can see that the Pattern is correct. But for some weird reason the script already matches at the 4th character after #
abc#abcd should not give a match, but is does.
Any suggestions ?
You need to be aware of RegExp constructor where escaped characters must be double-escaped. So, your regex string passed to the RegExp constructor should look like:
^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$
The fix can be introduced like this:
var RE = new RegExp($Pattern.replace(/\\/g, '\\\\'), 'i');
It will work if the escape symbols are used consistently.
I have written following code:
var date_regex = new RegExp("\d{2}[./-]\d{2}[./-]\d{4}", "gi");
var period = "27.03.2014 - 24.04.2014";
console.log(date_regex.exec(period));
I get console log : null.
I checked my code on this site and it says valid. What is wrong? Thanks for help!
\d{2}[./-]\d{2}[./-]\d{4}
Debuggex Demo of my RegEx
You need to escape your backslashes:
var date_regex = new RegExp("\\d{2}[./-]\\d{2}[./-]\\d{4}", "gi");
Just as a side note, you can avoid matching strings with mismatched delimiters such as "27.01-1444" by capturing the first delimiter and matching the same one for the second delimiter via \1:
var date_regex = new RegExp("\\d{2}([./-])\\d{2}\\1\\d{4}", "gi");
You are creating your regex from a string, so you need to escape the backslashes:
var date_regex = new RegExp("\\d{2}[./-]\\d{2}[./-]\\d{4}", "gi");
Or it's less complicated to use a regex literal:
var date_regex = /\d{2}[./-]\d{2}[./-]\d{4}/gi;
When creating a regular expression object (as opposed to the literal) with a string, you need to double escape slashes:
var date_regex = new RegExp("\\d{2}[./-]\\d{2}[./-]\\d{4}", "gi");
You'll discover that logging date_regex results in /d{2}[./-]d{2}[./-]d{4}/gi - not what we wanted!
However, you only need to use a string under certain conditions:
The regex involves a variable
The regex is formed in a loop (string prevents recompilation)
Thus, you'd be better off using a literal in this case:
var date_regex = /\d{2}[./-]\d{2}[./-]\d{4}/gi;
See MDN for more details on creating RegExp objects.
Combine the given answers and use .match to return all matches in an array.
var date_regex = /\d{2}[./-]\d{2}[./-]\d{4}/gi;
var range = "27.03.2014 - 24.04.2014";
console.log( range.match(date_regex) ); // [ "27.03.2014", "24.04.2014" ]
I am horrible with RegEx and I have been using this online tester for some time now and still can not find what I need.
So I have the string "2011_G-20_Cannes_summit". I want to replace all the underscores (_) with spaces.
So I want something like this:
var str = "2011_G-20_Cannes_summit";
str.replace(/_/g," "); or str.replace(/\_/g);
Though neither is working...
What am I missing?
That works fine. The replace method doesn't modify the existing string, it creates a new one. This will do what you want:
var str = "2011_G-20_Cannes_summit";
str = str.replace(/_/g," ");
I want to convert a string that looks like a regular expression...into a regular expression.
The reason I want to do this is because I am dynamically building a list of keywords to be used in a regular expression. For example, with file extensions I would be supplying a list of acceptable extensions that I want to include in the regex.
var extList = ['jpg','gif','jpg'];
var exp = /^.*\.(extList)$/;
Thanks, any help is appreciated
You'll want to use the RegExp constructor:
var extList = ['jpg','gif','jpg'];
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');
MDC - RegExp
var extList = "jpg gif png".split(' ');
var exp = new RegExp( "\\.(?:"+extList.join("|")+")$", "i" );
Note that:
You need to double-escape backslashes (once for the string, once for the regexp)
You can supply flags to the regex (such as case-insensitive) as strings
You don't need to anchor your particular regex to the start of the string, right?
I turned your parens into a non-capturing group, (?:...), under the assumption that you don't need to capture what the extension is.
Oh, and your original list of extensions contains 'jpg' twice :)
You can use the RegExp object:
var extList = ['jpg','gif','jpg'];
var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$");