Simple way to use variables in regex - javascript

This almost has the answer...
How do you use a variable in a regular expression?
I need to know if I can use variables instead of hardcode in the regex?
str1 = str1.replace(/abcdef/g, "stuvwxyz");
can I use variables instead of /abcdef/g and "stuvwxyz"

Of course that you can, every single bit of this can be dynamic:
var pattern = 'abcdef';
var input = 'stuvwxyz';
var modifiers = 'g';
var regex = new RegExp(pattern, modifiers);
var str1 = 'Hello abcdef';
str1 = str1.replace(regex, input);
Checkout the docs as well.

Yes.
var pattern = /abcdef/g;
var input = "stuvwxyz";
str1 = str1.replace(pattern, input);

Like this?
var regex = /abcdef/g;
var string = "stuvwxyz";
var str1 = "abcdef";
str1 = str1.replace(regex, string);

Related

How to use a variable in a match method with regular expression pattern

I want to get an array in JavaScript from a string, cutting it in half.
Example:
// From this:
var myStr = 'cocacola';
// To this:
var myArray = ['coca', 'cola'];
I tried the following method:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
// This won't work
var myArray = myStr.match(/.{1,strHalf}/g);
// Only this will work fine
var myArray = myStr.match(/.{1,4}/g);
You can do String.slice() to solve this
var myStr = 'cocacola';
let len = myStr.length;
let result = [myStr.slice(0, len/2), myStr.slice(len/2)]
console.log(result);
You'll need to to use the RegExp() constructor and make a string that it understands:
var regexString = "/.{1," + strHalf + "}/g";
var myRegex = new RegExp( regexString );
var myArray = myStr.match( myRegex );
...but be careful doing this; if strHalf is a string containing special characters like / then your RegExp will have weird behaviour.
You can create a non-hardcoded regexp by using the RegExp constructor:
var myArray = myStr.match(new RegExp('/.{1,'+strHalf+'}/g'));
The constructor has no clue that strHalf should be an integer, so make sure you can control that.
This is known to introduce a lot of security issues, please don't use this in production. Regexes are too often used when they shouldn't. If you ever use a regex, do look into other options
There are much better alternatives, but at least it's possible!
You dont need regex for that.
The easiest way is that:
var myStr = 'cocacola';
var strHalf = myStr.length / 2;
var array = [myStr.substr(0, strHalf),myStr.substr(strHalf, myStr.length)];
jsfiddle: https://jsfiddle.net/cudg8qc3/
You can just slice the string and place the first element in the first slot, and the second element in the second slot in the array.
var str_len = myStr.length
var my_array = [myStr.slice(0, str_len/2), myStr.slice(str_len/2, str_len)]

Using variables in a regular expression

I have this string replacement regular expression:
var res = myString.match(/[.,]/g);
Now I want to store the pattern in a variable:
var usedSeparator =".,";
var regExp = new RegExp("["+usedSeparator+"]","g");
var res = myString.match(regExp);
But it doesn't work. How could I do such thing?
Perhaps, you intended to use split(). Here, it works:
myString = "I have seen it, but I forgot the name."
usedSeparator =".,";
regExp = new RegExp("["+usedSeparator+"]","g");
res = myString.split(regExp);
alert(res);

Pattern match to get string between brackets

I am trying to find whatever string is in between the aggregate() and find(). Below is my code.
var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /((.*))/;
var result = str1.match(matchPharse);
console.log(result);
I am getting the result always the whole string instead of
[{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}]
I am searching for something like this
try this pattern instead:
var matchPharse = /((\[.*\]))/;
((\[.*?\]))
You Should use a non greedy expression.
Try the following RegEx:
var matchPharse= /\((.*)\)/g;
Matches any sequence between ().
This is a DEMO.
var str1 = 'aggregate([{$group:{_id:{state:"$state",city:"$city"},sum:{$sum:"$pop"}}},{$sort:{sum:1}},{$group:{_id:"$_id.state",smallestcity:{$first:"$_id.city"},smallest:{$first:"$sum"},largestcity:{$last:"$_id.city"},largest:{$last:"$sum"}}}])'
var str2 = 'find({awards:{$elemMatch:{award:"Turing Award",year:{$gt:1980}}}}).limit(0)'
var matchPharse = /\((.*)\)/;
var result = str1.match(matchPharse);
alert(result);
You just need to escape the outside parentheses. Try:
var matchPharse = /\((.*)\)/;
For just the content inside the parentheses use result[1]

Javascript regex value search

After reading the post here, I tried to get the value by regex as below:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
match[1]
The result was JKG&propertytype=3'></a>, but I only want JKG. Strictly speaking I want the value between &estate= and &ppt Could someone suggest how to do that?
Thanks
A Regular Expression:
/&estate=(.*?)&ppt=/g
Note: I wouldn't recommend using regular expressions to parse query strings. It's brittle. Consider if the variables in the query string change order. If that can be the case, I recommend reading - Parse query string in JavaScript.
do:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /estate=(.*)&ppt=/g;
var match = myRegexp.exec(myString);
console.log( match[1] );
If only the solution is important then you can use the following:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var indx1 = mystring.indexOf("&estate=") + 8;
var indx2 = mystring.indexOf("&ppt");
var neededString = mystring.substring(indx1, indx2);
Just exclude ampersands from the selection:
var myRegexp = /&estate=([^&]+)/g;
You might want to change it to this, in case estate is the first parameter:
var myRegexp = /[\?&]estate=([^&]+)/g;
jsFiddle
Based on your result value, just split it at the ampersand, no new or alternate regex required.
JavaScript:
var myString = "<a href='/search.html?id=HDJ&area=ASD&estate=JKG&ppt=3'></a>";
var myRegexp = /&estate=(.*?)(?:\s|$)/g;
var match = myRegexp.exec(myString);
var value = match[1].split('&')[0];
alert( value );

How to get variables from a string using regex in Javascript?

I have a javascript string variable like so:
var somestring = "mypattern_var1_var2";
How can I use regex to extract var1 & var2?
I would just use the split() method instead if it's that straightforward:
var somestring = "mypattern_var1_var2";
var tokens = somestring.split("_");
var var1 = tokens[1];
var var2 = tokens[2];
I know you specified regex, but is there a specific reason to use it?
An alternative would be to use the .split() method, which would probably be easier.
var somestring = "mypattern_var1_var2";
var results = somestring.split("_");
var var1 = results[1];
var var2 = results[2];
No need
var parts = somestring.split("_");
alert(parts[1] + ':' + parts[2])
Or get real fancy like How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?
And we MUST have jQuery in the equation: Regular expression field validation in jQuery
You could use a split() in this situation - given that you always know that you will have a pattern in the beginning, (given that the pattern doesn't contain any '_'s)
var somestring = "mypattern_var1_var2";
var example = somestring.split('_');
var1 = example[1];
var2 = example[2];
Demo

Categories

Resources