Using regex without creating a regex object - JavaScript - javascript

I have the following code that checks a URL if it contains a certain pattern:
var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript";
var patt = new RegExp('https?:\/\/[^/]+\.google\.[a-z.]+\/((search[?#])|(webhp[?#])|([?#])).*q=');
var check = patt.test(url);
alert(check);
The above regex won't work without using new RegExp(). How do I use the same regex without creating the regex object. For example, something like this (which doesn't seem to work):
var url = "https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=regex%20javascript";
var check = ('https?:\/\/[^/]+\.google\.[a-z.]+\/((search[?#])|(webhp[?#])|([?#])).*q=').test(url);
alert(check);

Do you mean a regex literal like so
var check = /https?:\/\/[^/]+\.google\.[a-z.]+\/((search[?#])|(webhp[?#])|([?#])).*q=/.test(url)
this is however merely syntactic sugar and does not free you of creating actual RegEx objects

Related

How do I pass a variable into regex with Node js?

So basically, I have a regular expression which is
var regex1 = /10661\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;
var result=text.match(regex1);
user_activity = result[1].replace(/\s/g, "")
console.log(user_activity);
What I'm trying to do is this
var number = 1234;
var regex1 = /${number}\" class=\"fauxBlockLink-linkRow u-concealed\">([\s\S]*?)<\/a>/;
but it is not working, and when I tried with RegExp, I kept getting errors.
You can use RegExp to create regexp from a string and use variables in that string.
var number = 1234;
var regex1 = new RegExp(`${number}aa`);
console.log("1234aa".match(regex1));
You can build the regex string with templates and/or string addition and then pass it to the RegExp constructor. One key in doing that is to get the escaping correct as you need an extra level of escaping for backslashes because the interpretation of the string takes one level of backslash, but you need one to survive as it gets to the RegExp contructor. Here's a working example:
function match(number, str) {
let r = new RegExp(`${number}" class="fauxBlockLink-linkRow u-concealed">([\\s\\S]*?)<\\/a>`);
return str.match(r);
}
const exampleHTML = 'Some link text';
console.log(match(1234, exampleHTML));
Note, using regex to match HTML like this becomes very order-sensitive (whereas the HTML itself isn't order-sensitive). And, your regex requires exactly one space between classes which HTML doesn't. If the class names were in a slightly different order or spacing different in the <a> tag, then it would not match. Depending upon what you're really trying to do, there may be better ways to parse and use the HTML that isn't order-sensitive.
I solved it with the method of Adem,
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
var number = 1234;
var firstPart = `<a href="/forum/search/member?user_id=${number}" class="fauxBlockLink-linkRow u-concealed">`
var regexpString = escapeRegExp(firstPart) + '([\\s\\S]*?)' + escapeRegExp('</a>');
console.log(regexpString)
var sample = ` `
var regex1 = new RegExp(regexpString);
console.log(sample.match(regex1));
in the first place the issue was actually the way I was reading the file, the data I was applying the match on, was undefined.

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

ng-pattern Vs script validation

I'm validating date (Format is YYYY/MM/DD) using regular expression ng-pattern. When i use below code in UI, it's working fine.
<input type="text" class="k-fill" ng-pattern="/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/" ng-model="Request.ExpDate" id="ExceptedDate" name="ExceptedDate" ng-readonly="true" required />
But i want to validate the pattern inside of a function for pop-up a validation message. For achieving it I used below code inside one of my js file.
var str = Request.ExpDate;
var x = '/((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/';
var patt = new RegExp(x);
var res = patt.test(str);
if res return false, I can show a message. But the problem is, it is returning false for every dates which are even in the right format.
May I know the reason for why the regexp is working fine with ng-pattern and why it is not working properly inside JS function?
Your regex returns false all the time because you included regex delimiters in the pattern that you initialize with a constructor notation (new RegExp(var)).
You do not have to use a constructor and can initialize RegExp using a regular literal in the form of /.../:
var str = Request.ExpDate;
var patt = /((^[1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))\/([0]{1}[1-9]{1}|[1]{1}[0-2]{1})\/([0]{1}[1-9]{1}|[1,2]{1}\d{1}|[3]{1}[0,1]{1})$/;
var res = patt.test(str);
However, it seems your regex has some issues in it, here is a fixed version:
/^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/
I removed {1} limiting quantifier since it is redundant, and removed , from inside the character classes [1,2] and [0,1] since the comma was treated as a literal, and could mess up the results. We can also further enhance by removing unnecessary groups or turning them to non-capturing, but those are already cosmetic changes.
See sample:
var str = "2992/10/31";
var patt = /^((199\d)|([2-9]\d{3}))\/(0[1-9]|1[0-2])\/(0[1-9]|[12]\d|3[01])$/;
var res = patt.test(str);
document.write(res);
Note that you could also make use of Date.Parse to validate the date more precisely.

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