Well, you can use this:
var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");
Answer from Derek 朕會功夫 on Stack OverflowWell, you can use this:
var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");
You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.
var oldWordRegEx = new RegExp(oldWord,'g');
myString.replace(oldWordRegEx,"");
A simple solution is not to use RegEx at all. Use Template literals
var module = 'm1',
taskId = 't1',
hash = 'h1';
var url = `/task/${module}?taskId=${taskId}#${hash}`;
var module = 'm1',
taskId = 't1',
hash = 'h1';
var url = `/task/${module}?taskId=${taskId}#${hash}`;
document.body.innerHTML = url;
Using RegEx:
function replaceUrl(url, data) {
// Create regex using the keys of the replacement object.
var regex = new RegExp(':(' + Object.keys(data).join('|') + ')', 'g');
// Replace the string by the value in object
return url.replace(regex, (m, $1) => data[$1] || m);
}
function replaceUrl(url, data) {
var regex = new RegExp(':(' + Object.keys(data).join('|') + ')', 'g');
return url.replace(regex, (m, $1) => data[$1] || m);
}
var updatedUrl = replaceUrl('/task/:module?taskId=:taskId#:hash', {
module: 'm1',
taskId: 't1',
hash: 'h1'
});
console.log(updatedUrl);
document.body.innerHTML = updatedUrl;
You could write a very simple templating function to achieve this in ES5:
function template(string, obj){
var s = string;
for(var prop in obj) {
s = s.replace(new RegExp('{'+ prop +'}','g'), obj[prop]);
}
return s;
}
template('/task/{module}?taskId={taskId}#{hash}', {
module: 'foo',
taskId: 2,
hash: 'bar'
});
Fiddle: https://jsfiddle.net/j5hp2cfv/
How to run a javascript replace function with a string of a variable?
Nice simple one for the javascript legends: is it possible to use .replace with a variable?
node.js - Javascript find and replace string with variable values - Stack Overflow
javascript - Replace part of string with variable - Stack Overflow
Hello you lovely people. I'm very early on on my javascript learning curve but look forward to the day I can help others as I do with other things I am technically proficient with.
Minimal, Reproducible Example:
Desired behaviour:
I am trying to use multiple .replace and have it working like:
{{$json["data"].replace('data1','output1').replace('data2','output2')}}
Specific problem or error:
What I can't seem to get to work is when the .replace is coming from a variable instead of being typed manually.
Shortest code necessary to reproduce the problem:
Examples of some code that I have tried using different characters in-between like + and &, etc:
{{$json["data"]+$json["replaceList"]}} and {{$json["data"]++$json["replaceList"]}} and {{$json["data"]&$json["replaceList"]}} and {{$json["data"]&&$json["replaceList"]}} and {{$json["data"].$json["replaceList"]}} and {{$json["data"]$json["replaceList"]}} etc.
(Where replaceList is: .replace('data1','output1').replace('data2','output2')
I would be deeply appreciative if anyone can spare a few seconds to suggest how my code should be formatted for it to work.
Although no idea if it'll help, below is the code from that entire node:
{ "meta": { "instanceId": "fa2d1642edbdc8ac49f8128b966e8120dd7f1a0f00530c44a45a62640a08c14d"}, "nodes": [ { "parameters": { "keepOnlySet": true, "values": { "string": [ { "value": "={{ $json["data"] }}" } ] }, "options": {} }, "id": "383c09c2-e60f-4b52-8ece-2c2e39721aaa", "name": "Set2", "type": "n8n-nodes-base.set", "typeVersion": 1, "position": [ 1900, 520 ] } ], "connections": {} }
Thank you so so much in advance and warmest regards
Cheers!
Your current regex extracts all the text contained within {{}} with its capture group. But you only want the index of the replacement, which is contained within the [], and not the entire string itself. So you have two options:
- Modify regex to capture only the index, so that would look like
/{{field\[(.+?)\]}}/, where the capture group now only takes the number within the brackets. - Leave the original regex alone, but change the replace function to extract the number from the returned match. In this case you'll have a second regex (or some other method) to extract the number from the matched string (in this case, get
"10"out of"field[10]").
Here's an example demonstrating both:
var string = 'This is some content: {{field[10]}}';
var submission = {inputs: []};
submission.inputs[10] = 'replace value';
// I want the new string to be this
// var newString = 'This is some content: replace value';
var newString = string.replace(/{{field\[(.+?)\]}}/g, (match, cap1) => submission.inputs[cap1]);
console.log(newString)
// OR:
var otherNewString = string.replace(/\{{(.+?)}}/g, (match, cap1) => submission.inputs[cap1.match(/\[(.+?)\]/)[1]]);
console.log(otherNewString)
You can use the following regex to extract the contents between {{field[ and ]}} as the snippet below shows. The snippet uses a callback in the replace function and passes the captured group's value to it so that an appropriate value may be returned (submission.inputs[b] where b is the number you want: 10 in this case).
{{[^[]+\[([^\]]+)]}}
{{Match this literally[^[]+Match any character except[one or more times\[Match[literally([^\]]+)Capture any character except]one or more times into capture group 1. This is the value you want]}}Match this literally
var string = 'This is some content: {{field[10]}}'
var submission = {inputs:[]}
submission.inputs[10] = 'replace value'
var newString = string.replace(/{{[^[]+\[([^\]]+)]}}/g, function(a, b) { return submission.inputs[b] })
console.log(newString)
The RegExp constructor takes a string and creates a regular expression out of it.
function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
If replaceWhat might contain characters that are special in regular expressions, you can do:
function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
See Is there a RegExp.escape function in Javascript?
The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags
Replace has an alternate form that takes 3 parameters and accepts a string:
function name(str,replaceWhat,replaceTo){
str.replace(replaceWhat,replaceTo,"g");
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
If I understand correctly for this to work as dynamically as you state you will have to do the following
// example variable, you need to use var so its
// available on the window otherwise this will not work
var categoryName = "movies";
...
let searchUrl = "category/[categoryName]/all";
let regex = /\[(.+?)\]/ug;
let variableName = searchUrl.match(regex)[0];
searchUrl = searchUrl.replace(regex, window['variableName']);
Your dynamic variable will have to be stored globally for this work!
You're so close! What you have now tries to replace [categoryName] with the global variable $1, which doesn't exist. What you want is to use searchUrl.replace(regex, categoryName), assuming categoryName is dynamically set with the correct category.