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 Overflow
Discussions

How to run a javascript replace function with a string of a variable?
Hi, I’m trying to replace a word that appears multiple times in a text variable. Trying a yarn text replacement workaround. And I think that for now the javascript function replace could be the only way to achieve that while we don’t have any manipulation of text that can do it. More on forum.gdevelop.io
🌐 forum.gdevelop.io
6
0
December 12, 2019
Nice simple one for the javascript legends: is it possible to use .replace with a variable?
This sounds a lot like an XY problem . I don't think the approach you've taken to whatever problem you have is the way to go, and would recommend trying to clarify the problem rather than the current solution. When you use dot notation or bracket notation with a variable, you are attempting to access the property of an object with the given name. Calling .replace on a string works because strings are turned into String objects when you attempt to access a property from them, and String objects have a replace method on their prototype. See replace . It is very unclear what you mean when you say "Where replaceList is...", and don't show how the variable is actually defined. You can't just assign property accessor chains to a variable. I assume what you are trying to do is something like the following, although I warn that this is a terrible idea: const example = "data1, data2"; String.prototype.replaceList = function replaceList() { return this.replace("data1", "data3").replace("data2", "data4"); } console.log(example.replaceList()); This adds a method to all String objects which is hard-coded to do exactly what you are trying to do. This is bad because it needlessly adds a method to all String objects (this really should never be necessary), and also because it is hard-coded instead of flexible. Instead of this, you could just use a function that takes a string and returns a new string. const p = "data1, data2"; function replaceList(str, tupleList) { let result = str; tupleList.forEach(([pattern, replacement]) => { result = result.replace(pattern, replacement); }); return result; } console.log(replaceList(p, [["data1", "data3"], ["data2", "data4"]])); // data3, data4 This may still not be the best strategy, depending on the actual problem or given more specific context, but it at least doesn't pollute the global String prototype. More on reddit.com
🌐 r/learnjavascript
3
4
April 11, 2023
node.js - Javascript find and replace string with variable values - Stack Overflow
Modify regex to capture only 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, ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Replace part of string with variable - Stack Overflow
I have the following string: documentation/:docsID/items Now I want to replace the :docsID by a variable. So if the variable is equal to 12, i want the link look like documentation/12/items. How ca... More on stackoverflow.com
🌐 stackoverflow.com
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › replace
String.prototype.replace() - JavaScript - MDN Web Docs
The replace() method of String values returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence ...
🌐
GDevelop
forum.gdevelop.io › how do i...?
How to run a javascript replace function with a string of a variable? - How do I...? - GDevelop Forum
December 12, 2019 - Hi, I’m trying to replace a word that appears multiple times in a text variable. Trying a yarn text replacement workaround. And I think that for now the javascript function replace could be the only way to achieve that…
🌐
Coursesweb
coursesweb.net › javascript › replace-javascript-variable-name-from-string-with-value_cs
Replace JavaScript variable name from string with its value
Returns that string with variable names replaced function replaceStrVar(str){ // JavaScript & jQuery Courses - https://coursesweb.net/javascript/ str = str.replace(/%(.*?)%/gi, function(a,b) { // if token is an array item, else, is object property, or variable if(b.match(/[a-z0-9_]+\[[a-z0-9_]+\]/i)) { var arritm = b.match(/([a-z0-9_]+)\[([a-z0-9_]+)\]/i); // gets an array with the matched items return window[arritm[1]][arritm[2]]; } else { var voitm = b.split('.'); return (voitm.length == 2) ?
🌐
freeCodeCamp
freecodecamp.org › news › javascript-replace-how-to-use-the-string-prototype-replace-method-js-example
JavaScript Replace – How to Use the String.prototype.replace() Method JS Example
February 8, 2022 - This method works for regular expressions, too, so the item you're searching for may be expressed as a regular expression. The value to return as the replaced value may be expressed as a string or function. const variable = variable.replace(...
🌐
Reddit
reddit.com › r/learnjavascript › nice simple one for the javascript legends: is it possible to use .replace with a variable?
r/learnjavascript on Reddit: Nice simple one for the javascript legends: is it possible to use .replace with a variable?
April 11, 2023 -

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!

Top answer
1 of 3
6
This sounds a lot like an XY problem . I don't think the approach you've taken to whatever problem you have is the way to go, and would recommend trying to clarify the problem rather than the current solution. When you use dot notation or bracket notation with a variable, you are attempting to access the property of an object with the given name. Calling .replace on a string works because strings are turned into String objects when you attempt to access a property from them, and String objects have a replace method on their prototype. See replace . It is very unclear what you mean when you say "Where replaceList is...", and don't show how the variable is actually defined. You can't just assign property accessor chains to a variable. I assume what you are trying to do is something like the following, although I warn that this is a terrible idea: const example = "data1, data2"; String.prototype.replaceList = function replaceList() { return this.replace("data1", "data3").replace("data2", "data4"); } console.log(example.replaceList()); This adds a method to all String objects which is hard-coded to do exactly what you are trying to do. This is bad because it needlessly adds a method to all String objects (this really should never be necessary), and also because it is hard-coded instead of flexible. Instead of this, you could just use a function that takes a string and returns a new string. const p = "data1, data2"; function replaceList(str, tupleList) { let result = str; tupleList.forEach(([pattern, replacement]) => { result = result.replace(pattern, replacement); }); return result; } console.log(replaceList(p, [["data1", "data3"], ["data2", "data4"]])); // data3, data4 This may still not be the best strategy, depending on the actual problem or given more specific context, but it at least doesn't pollute the global String prototype.
2 of 3
2
If you want to parse a string as if it's source code you can use the "eval" method. However There are approximately zero good reasons to ever do this. It creates a real and actual security vulnerability. You will fail interviews for real jobs if you use it. What is it you're really trying to do? Recursively parse some data?
Find elsewhere
Top answer
1 of 2
3

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)

2 of 2
2

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)

🌐
W3Schools
w3schools.com › jsref › jsref_replace.asp
JavaScript String replace() Method
The replace() method returns a new string with the value(s) replaced.
🌐
Coder's Block
codersblock.com › blog › javascript-string-replace-magic
JavaScript String Replace Magic - Will Boyd / Coder's Block
Replacing strings in JavaScript ... The most obvious way to do string replacement is by passing 2 strings to replace(), the string to find and the string to replace it with....
🌐
Stack Overflow
stackoverflow.com › questions › 75375670 › replace-something-inside-a-string-with-variables
javascript - Replace {something} inside a string with variables - Stack Overflow
// Input array const arr = [ "string 1 have {amount}", "string 2 have {amount} as well as {user}", "string 3 have {amount} as well as {user} and their {bank.balance}" ]; // Variables holding the values const amount = Math.floor(Math.random() * 100) + 1; const user = 'Alpha'; const bank = { balance: 500 }; // Iterating the array to map the values against each '{...}' const res = arr.map(str => { // replacing the '{' with '${' to support the template literal format.
🌐
Career Karma
careerkarma.com › blog › javascript › javascript replace(): a step-by-step guide
JavaScript Replace(): A Step-By-Step Guide | Career Karma
December 1, 2023 - This variable contains the value This string is interesting. On the next line, we replace the word interesting with intriguing, using the JavaScript string replace() method.
🌐
TechOnTheNet
techonthenet.com › js › string_replace.php
JavaScript: String replace() method
Let's take a look at an example of how to use the replace() method in JavaScript. The simplest way to use the replace() method is to find and replace one string with another string. This method does not involve regular expression objects. ... In this example, we have declared a variable called ...
🌐
Linux Hint
linuxhint.com › string-replace-method-in-javascript-explained
Linux Hint – Linux Hint
July 13, 2022 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
freeCodeCamp
freecodecamp.org › news › javascript-replace-how-to-replace-a-string-or-substring-in-js
JavaScript Replace – How to Replace a String or Substring in JS
November 7, 2024 - For example, in the text below, ... the color of a webpage's background, text, and elements." You can do that by chaining as many replace() methods ......
🌐
n8n
community.n8n.io › questions
Hopefully a nice simple one: is it even possible to use .replace with a variable? - Questions - n8n Community
April 11, 2023 - Describe the problem/error/question 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 proficent with. Minimal, Reproducible Example: Desired behaviour: I am trying to use multiple .replace and currently have it working in a ‘Set’ node 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 data I want to...