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

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

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

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 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.

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