JavaScript Find and replace with variable in regular expression [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression Pattern With A Variable
function function1() {
var key = "name";
var sample = "param.name['key'] = name; param.name[i] = 1000; param.name1[i] = name1;";
var result = result.replace(/param.<<name>>\[(\d+)\]/g, 'parameter[prefix_$1]');
}
Expected result: parameter['prefix_key'] = name; parameter['prefix_i'] = 1000;
I cant add variable key into the replace function in regular expresssion.
Please help how to construct the regular expression in replace

You can make a regex out of a string by making a RegExp object:
var regex = new RegExp("param\\." + name + "\\[(\d+)\\]", "g")
var result = result.replace(regex, 'parameter[prefix_$1]');

Related

Javascript - split values inside parentheses [duplicate]

This question already has answers here:
How to get function parameter names/values dynamically?
(34 answers)
Closed 3 years ago.
I am trying to split the following string:
delete(value1,value2);
I want to get the values and save them in a array:
var values = [value1,value2]
A regex would do the trick:
/\((.*)\)/g.exec('delete(value1,value2);')[1].split(',')
This captures anything between parentheses, which you can then split again.
You can split the string using split function
var str = "delete(value1,value2)";
var stringArray = str.split("(");
var values=stringArray[1].split(",");
use Replace method to finally delte ")" from second string in array
values[1]=values[1].replace(")","");
How about:
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(fnStr) {
var fnStr = fnStr.replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if(result === null)
result = [];
return result;
}
var str = "delete(value1,value2)";
getParamNames(str);

multiple string replace using variable [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I have to replace multiple words in a string.
my code is like this
var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
console.log(finalPrice.replace(csku, value));
Using this code I got this solution
({con}*5)+{wid}+{fixed_var}+{extra}+{sqft}+{len}
but I want this
({con}*5)+{wid}+{fixed_var}+{extra}+{sqft}+5
I google it for replacing multiple words in the string using one call I find this
str.replace(/X|x/g, '');
Here / and g is used for multiple replace and in this format I have to add static word but in my code csku is not fixed so how can I replace all words in one call using variable
Using the code from the duplicate to create a Regex object using the variable
var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
var re = new RegExp(csku, "g");
console.log(finalPrice.replace(re, value));
use new RegExp(cksu, 'g') to create a regular expression that'll match all cksu.
new RegExp('{len}', 'g') will return /{len}/g meaning all global matches.
so finalPrice.replace(new RegExp(cksu, 'g'), value) will replace all global matches of cksu with value.
var csku = "{len}";
var value = 5;
var finalPrice = "({con}*{len})+{wid}+{fixed_var}+{extra}+{sqft}+{len}";
console.log(finalPrice.replace(new RegExp(csku, 'g'), value));
Standart replace function change just first match. You can use this function:
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}

pass variable to replace function regular expression javascript [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 6 years ago.
I want to have a 'newline'-function to pass a string to it and print it on pdf. my function so far is
var array = new Array();
function newLineFunction_PDF(text) {
var arr = text.replace(/.{70}\S*\s+/g, "$&#").split(/\s+#/);
return arr;
}
array = newLineFunction_PDF('some Text');
for( var i in array) {
print(array[i]);
}
What it does is cut the text in to pieces of length-70 incl. the last word, push it into the array and print it afterwards with new lines. Now i want to pass a number to the function, like 100, so i can decide the max-length of the text per line.
So far I tried:
function newLineFunction_PDF(text, num) {
var re = new RegExp(/.{num}\S*\s+/g);
var arr = text.replace(re, "$&#").split(/\s+#/);
return arr;
}
but I dont know how and where to add escapes into the new RegExp.
The parameter of Regexp is a string:
var re = new RegExp('.{' + num + '}\S*\s+', 'g');

Javascript regex test from variable [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 6 years ago.
I have an problem with constructing regex from variable.
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\(2n\+1\)';
console.log(selector.test(a))//true
var reg = new RegExp(s,"g");
console.log(reg.test(a) )//false
Second is false because I have string quotes around it (I think), how do I construct regexp from string?
https://jsfiddle.net/eq3eu2e8/1/
For a string you have to use double backslashes if you want to include them in the string:
var a = '.playlist-item:nth-child(2n+1)';
var selector = /.playlist-item:nth-child\(2n\+1\)/g;
var s = '.playlist-item:nth-child\\(2n\\+1\\)';
console.log(selector.test(a)); //true
var reg = new RegExp(s,"g");
console.log(reg.test(a)); //false

How to dynamically create regex to use in .match Javascript? [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 8 years ago.
I need to dynamically create a regex to use in match function javascript.
How would that be possible?
var p = "*|";
var s = "|*";
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(/"p"(\d{3,})"s"/g)
this would be the right regex: /\*\|(\d{3,})\|\*/g
even if I add backslashes to p and s it doesn't work. Is it possible?
RegExp is your friend:
var p = "\\*\\|", s = "\\|\\*"
var reg = new RegExp(p + '(\\d{3,})' + s, 'g')
"*|1387461375|* hello *|sfa|* *|3135145|* test".match(reg)
The key to making the dynamic regex global is to transform it into a RegExp object, and pass 'g' in as the second argument.
Working example.
You can construct a RegExp object using your variables first. Also remember to escape * and | while forming RegExp object:
var p = "*|";
var s = "|*";
var re = new RegExp(p.replace(/([*|])/g, '\\$1')
+ "(\\d{3,})" +
s.replace(/([*|])/g, '\\$1'), "g");
var m = "*|1387461375|* hello *|sfa|* *|3135145|* test".match(re);
console.log(m);
//=> ["*|1387461375|*", "*|3135145|*"]

Categories