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

javascript - How do you use a variable in a regular expression? - Stack Overflow
But obviously, this will only replace the text "replaceThis"...so how do I pass this variable into my regex string? ... Note that we're currently working on adding this functionality to JavaScript if you have an opinion about it please join the discussion. More on stackoverflow.com
🌐 stackoverflow.com
RegEx - Find and Replace with Variables - Actions - Help & Questions - Drafts Community
I am trying to figure out how to use Find & Replace with RegEx to manipulate text. In this case, want to set a variable using RegEx and then replace text with the variable. Text: Mr. John Smith Mr. XX goes to town. S… More on forums.getdrafts.com
🌐 forums.getdrafts.com
0
January 6, 2020
Hopefully a nice simple one: is it even possible to use .replace with a variable?
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 ... More on community.n8n.io
🌐 community.n8n.io
1
0
April 11, 2023
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
🌐
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 - February 8, 2022 / #JavaScript · Kolade Chris · The String.prototype.replace() method searches for the first occurrence of a string and replaces it with the specified string. It does this without mutating the original string.
🌐
Drafts Community
forums.getdrafts.com › actions - help & questions
RegEx - Find and Replace with Variables - Actions - Help & Questions - Drafts Community
January 6, 2020 - I am trying to figure out how to use Find & Replace with RegEx to manipulate text. In this case, want to set a variable using RegEx and then replace text with the variable. Text: Mr. John Smith Mr. XX goes to town. Script // define regex to use... const findRegex = /([M][r-s]\.\s)(\w*\s)(\w*)/g; // define replacement expression... const FirstName = "$2"; const LastName = "$3"; //Find Text const XX = "XX"; // // do the replacement... draft.content = draft.content.replace(XX, LastName); dra...
🌐
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) ?
🌐
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 ...
🌐
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...
Find elsewhere
🌐
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…
🌐
SheCodes
shecodes.io › athena › 2749-how-to-replace-one-item-with-another-in-javascript
[JavaScript] - How to Replace One Item with Another in | SheCodes
Learn how to use the `replace()` function in JavaScript to search and replace text in a string. Check out this MDN web docs page for more info. ... if I have a variable outside a function, do I need to redefine that variable inside the function?
Top answer
1 of 3
3

The biggest issue, I think, is that you are not just running a regex, but also running a replace over the entire HTML multiple times. And you are setting the actual DOM HTML multiple times rather than manipulating a string until you get the result, and then setting the HTML once. I would strongly recommend using a library like Handlebars.js, but if you want to do it yourself, a very quick implementation would be something like:

var translations = { 
    heading: { 
        hello: "hello" 
    }, 
    txt: { 
        welcome: "welcome" 
    }, 
    image: { 
        description: "this is a test" 
    }
};

function get(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

function replaceTokens(HTML) {
    return HTML.split('{{').map(function(i) { 
        var symbol = i.substring(0, i.indexOf('}}')).trim(); 
        return i.replace(symbol + '}}', get(translations, symbol)); 
    }).join('');
}
2 of 3
1

You can use your regexp (with a little modification) to split your html in an array. Then you can replace only the template chunks of your array by their translations, and finally joining it and replacing the document html with it :

var html = "a little {{foo}} in the {{bar}}"; // replace with document.documentElement.innerHTML
var translations = {foo: "boy", bar: "garden"};
var chunks = html.split(/({{[a-z.]+}})/g);
var chunksTranslated = chunks.map(function(chunk){
  if(chunk.slice(0,2)==="{{" && chunk.slice(-2)==="}}") {
    var id = chunk.slice(2,-2);
    return translations[id];
  }
  return chunk;
});
var translatedHtml = chunksTranslated.join("");
//document.documentElement.innerHTML = translatedHtml;
🌐
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 ...
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)

🌐
Tom McFarlin
tommcfarlin.com › local-variables-with-javascripts-replace-function
Local Variables with JavaScript’s Replace | Tom McFarlin
October 18, 2010 - I was storing the encoded representation of the ampersand in a local variable named _ampersand and had a function that accepted the full query string to be sent to the server, encode the data, perform some additional processing, and then return it. ... function encodedData(strInput) { // irrelevant code removed... return strInput.replace(/&/g, _ampersand); }
🌐
Coder's Block
codersblock.com › blog › javascript-string-replace-magic
JavaScript String Replace Magic - Will Boyd / Coder's Block
The g flag is crucial. That’s what makes it a global search, finding all occurrences. But what if you want to specify a string to replace via a variable, instead of hardcoding “badger”? It’s a little more typing, but not hard to do with a RegExp object.
🌐
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 - In this example, the replace() method replaces the first occurrence of the word "JavaScript" with "Python" in the originalString variable.