Creating a dynamic RegExp pattern to include a variable value - javascript

I have a RegExp that I would like to make dynamic and create in a string. I want to change this:
var result:Object = value.match(/John\/(.*?) /);
to this:
var firstName:String = "John";
var result:Object = value.match(firstName + "\/(.*?) "); // this doesn't work
I'm using ActionScript but I think what would work in JavaScript would work as well here.

In Javascript you can create a new instance of the RegExp class:
var firstName:String = "John";
var result:Object = value.match(new RegExp(firstName + "\/(.*?) "));
When you use value.match(firstName + "\/(.*?) "); the first parameter to the match function is a string, but it should be a regular expression object.

Related

Is it possible to pass the variable instead of constant number in replace method

in the below code comma is placed after every 3 digits
{
var commaString = valueWthOutComma.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
is it possible to pass any variable in place of "3" in the above RegEx what I want is
{
var comma_place = 2 ; //any value can be place
var commaString = valueWthOutComma.replace(/\B(?=(\d{comma_place})+(?!\d))/g, ",");
}
To do what you require you would need to build the regex as a string instead of a literal, and provide it to the RegExp() constructor, something like this:
var comma_place = 2; //any value can be place
var re = new RegExp('\B(?=(\d{' + comma_place + '})+(?!\d))', 'g');
// var re = new RegExp(`\B(?=(\d{${comma_place}})+(?!\d))`, 'g'); // ES6 - won't work in IE
var commaString = valueWthOutComma.replace(re, ",");

Regular expression to eliminate a word

I have this string:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
I need to do a method that erases a certain word with regular expressions.
Example:
var word = "familyId";
var newChain = deleteParam(chain, word);
console.log(newChain);
Result = "providerId=12$brandId=1122112$officeId=21&";
Delete : familyId=123&
I tried to do the method in the following way, but it does not work:
function deleteParam(chain, word) {
var exp = new RegExp(param, "=[0-9]&");
var str = chain.replace(exp, ""); // Delete
return str
}
Please, I need your help, I can not make this method work, because I do not understand well how to build regular expressions.
Excuse me all, English is not my native language
thank you very much to all.
You can use something like this new RegExp(param + "=\[^&]+")
Here is an example:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
var toRemove = "familyId";
var pattern = new RegExp(toRemove + "=[^&]*&");
var newChain = chain.replace(pattern, "");
console.log(newChain);
If you're looking to process a GET request's search parameters is better to use a pattern like this (&|\?)*parameterName=[^&]*

jQuery Regex from String

I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true

Find Character & Make Capitlise in Javascript

I've a email as string (let's say "testdrive#gmail.com") and I want to check if email contains character "test" then capitalize that
(ex. testdrive#gmail.com = "TESTdrive#gmail.com", drivetest#gmail.com= "driveTEST#gmail.com"...).
How do I get this in JavaScript?
Thanks!
You can do it with the String.prototype.replace and String.prototype.toUpperCase functions like this:
var original = "testdrive#gmail.com"
var replaceTerm = 'test';
var modified = original.replace(replaceTerm, replaceTerm.toUpperCase());
console.log(modified); //logs TESTdrive#gmail.com
Javascript's replace method is the easiest way to find and replace an exact keyword. The first parameter is the string you are searching for. The second is what you want to replace that string with.
var str = "testdrive#gmail.com";
var x = str.replace('test', 'TEST');
console.log(x); //TESTdrive#gmail.com
function capitalizer() {
var mail = "drivetest#gmail.com";
var srchStr = "test";
var n = mail.search(srchStr);
var capitalized = mail.replace(srchStr,mail.substr(n, srchStr.length).toUpperCase());
document.getElementById("demo").innerHTML = capitalized;
}

Optimize regular expression for path replacement

I have following string var foo = require('foo/bar'); which I want to change to var foo = require('../../foo/bar');.
So far I wrote following code which would do this:
var search = 'foo/bar';
var replace = '../../foo/bar';
var regex = new RegExp('require[(](\"|\')' + search + '(\"|\')[)]', 'g');
var source = 'var foo = require(\'foo/bar\')';
source.replace(regex, 'require(\'' + replace + '\')');
However as you see this is very inefficient. What could I do to make this regex a bit shorter. For example:
only have to replace the path and not to rewrite require with require(\'' + replace + '\')'
make (\"|\') and [(] shorter
anything else?
Best,
Bo
Edit:
I am doing this replacement on complete javascript source files.
Edit2:
What is necessary to change var foobar = require('foo/bar'); to var foobar = require('../../foo/baz/bar') when foo/ and ../../foo/baz/ should be variable?
You can use this code:
var search = 'foo/bar';
var source = "var foo = require('foo/bar')";
var regex = new RegExp('(require)\\((["\'])(' + search + ')\\2\\)', 'g');
var repl = source.replace(regex, "$1('../../$3')");
//=> var foo = require('../../foo/bar')
Here is an alternative :
var str = "var foo = require('foo/bar');";
str = str.split(/(')/);
str.splice(2, 0, '../../');
str = str.join('');
Even simpler :
"var foo = require('foo/bar');".replace(/'([^']+)'/, "'../../$1'")
I wonder if you could do the replacement before wrapping your path inside the var xxx = require() statement.
Optimizing code that starts by undoing what has been done just before seems a bit inefficient.
Besides, it seems you already know the target path (foo/bar in your example), but it is not even necessary to use that.
The regexp here boils down to splitting the string after the opening quote and inserting the ../../ prefix.
You could do that with
source = source.split(/["']/,2).join('"../../')+'");';
The regexp is a constant, so you could put it into a variable to have it compiled once and for all.
That would probably be more efficient than generating and recompiling the regexp from your example each time.
But anyway, I wonder how many such strings you would have to replace to start noticing a performance hit.

Categories