variable in regular expression not working in jquery - javascript

I want to use variable in expression for auto increment id on add more. but when I add variable in expression it won't work and when I statically enter string "_1" in expression it work Here is code
$(document).ready(function() {
var row_number_current = 1;
var row_number_increment = Number(row_number_current);
row_number_increment += 1;
var addMore = '<div id="data_box_1"><label for="chart-pie-text_1">Chart Text</label></div>';
var row1 = addMore.replace("/_"+row_number_current+"/g", '_'+row_number_increment);
var row2 = addMore.replace(/_1/g, '_'+row_number_increment);
alert(row1);
alert(row2);
});
result of row1 is
<div id="data_box_1"><label for="chart-pie-text_1">Chart Text</label></div>
and row2 result is
<div id="data_box_2"><label for="chart-pie-text_2">Chart Text</label></div>

"/_"+row_number_current+"/g" is a string, not a regex. You need to construct a regex using this string, then pass that as the pattern argument in replace:
var regex1 = new RegeExp("_"+row_number_current,"g");
var row1 = addMore.replace(regex1, '_'+row_number_increment);
In your particular case, however, you don't really need a regex. Just use a string:
var row1 = addMore.replace(row_number_current, row_number_increment, "g");

In order to use variables in regular expressions, you have to create new RegExp object and pass your expression as the first string argument:
var regex = new RegExp("_" + row_number_current, "g");
row1 = addMore.replace(regex, "_" + row_number_increment);

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

remove chars in String javascript Regex

I have a chain like this of get page
file.php?Valor1=one&Valor2=two&Valor3=three
I would like to be able to delete the get request parameter with only having the value of it. for example , remove two
Result
file.php?Valor1=one&Valor3=three
Try with
stringvalue.replace(new RegExp(value+"[(&||\s)]"),'');
Here's a regular expression that matches an ampersand (&), followed by a series of characters that are not equals signs ([^=]+), an equals sign (=), the literal value two and either the next ampersand or the end of line (&|$):
/&[^=]+=two(&|$)/
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(/&[^=]+=two/, '');
console.log(output);
If you're getting the value to be removed from a variable:
let two = 'two';
let re = RegExp('&[^=]+=' + two + '(&|$)');
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '');
console.log(output);
In this case, you need to make sure that your variable value does not contain any characters that have special meaning in regular expressions. If that's the case, you need to properly escape them.
Update
To address the input string in the updated question (no ampersand before first parameter):
let one = 'one';
let re = RegExp('([?&])[^=]+=' + one + '(&?|$)');
let input = 'file.php?Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '$1');
console.log(output);
You can use RegExp constructor, RegExp, template literal &[a-zA-Z]+\\d+=(?=${remove})${remove}) to match "&" followed by "a-z", "A-Z", followed by one or more digits followed by "", followed by matching value to pass to .replace()
var str = "file.php?&Valor1=one&Valor2=two&Valor3=three";
var re = function(not) {
return new RegExp(`&[a-zA-Z]+\\d+=(?=${not})${not}`)
}
var remove = "two";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "one";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "three";
var res = str.replace(re(remove), "");
console.log(res);
I think a much cleaner solution would be to use the URLSearchParams api
var paramsString = "Valor1=one&Valor2=two&Valor3=three"
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
//Each element will be [key, value]
for (let p of searchParams) {
if (p[1] == "two") {
searchParams.delete(p[0]);
}
}
console.log(searchParams.toString()); //Valor1=one&Valor3=three

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

regular expression for [allchars]

I am trying to match something like [allchar] with a regular expression and be able to pull it out and replace it with other content
Here is what I am trying
var text = "[abc123.;.] this is more content";
var replacewith = "[contentreplacedwith]";
reg = new RegExp("/\[{1}.*?\]{1}/g");
if(reg.test(text))
{
txt = $('#message').val().replace(text,'[' + replacewith + ']');
console.log(txt);
}
The result should be
[contentreplacedwith] this is more content
reg = new RegExp("\\[.*?\\]", "g");
x = "[abc123.;.] this is more content";
console.log(x.replace(reg, "[contentreplacedwith]"));
If you use RegExp constructor the there's no need to pass / delimiters and the options like g for global are a second argument.

Creating a dynamic RegExp pattern to include a variable value

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.

Categories