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;
}
Related
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);
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, ",");
javascript, what is the best way to replace following two scenario.
It is possible to use replace and add regex to do this, if yes, how?
I want to convert "aaa.bbb.ccc" TO "aaa.bbb.*"
I want to convert "aaa.bbb.ccc.ddd.eee" TO "aaa.bbb.*.ddd.*"
var map = 'qwertyuiopasdfghjklzxcvbnm'.split('');
var rand = function(){
var len = map.length,
arr = [],
i;
for (i = 0; i < 3; i++){
arr.push(map[Math.floor(Math.random()*len)]);
}
return arr.join('');
};
var randStr = [rand(), rand()];
/* ASSUME above code is how you get random string */
var string = 'aaa.bbb.' + randStr[0] + '.ddd.' + randStr[1];
// use new RegExp() to parse string as regular expression
var regexp = new RegExp(randStr[0] + '|' + randStr[1], 'gi');
console.log(string.replace(regexp, '*'));
Read more about new RegExp() here (easy one), here (detailed one) and here (working example).
You should be able to apply this concept in your code now.
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
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');