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/
javascript - How do you use a variable in a regular expression? - Stack Overflow
RegEx - Find and Replace with Variables - Actions - Help & Questions - Drafts Community
Hopefully a nice simple one: is it even possible to use .replace with a variable?
How to run a javascript replace function with a string of a variable?
Instead of using the /\sREGEX\s/g syntax, you can construct a new RegExp object:
// variable == 'REGEX'
let re = new RegExp(String.raw`\s${variable}\s`, "g");
You can dynamically create regex objects this way. Then you will do:
"mystring1".replace(re, "newstring");
For older browser or node
// variable == 'REGEX'
var re = new RegExp("\\s" + variable + "\\s", "g");
"mystring1".replace(re, "newstring");
As Eric Wendelin mentioned, you can do something like this:
str1 = "pattern"
var re = new RegExp(str1, "g");
"pattern matching .".replace(re, "regex");
This yields "regex matching .". However, it will fail if str1 is ".". You'd expect the result to be "pattern matching regex", replacing the period with "regex", but it'll turn out to be...
regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex
This is because, although "." is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful:
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};
Then you can do:
str1 = "."
var re = new RegExp(RegExp.quote(str1), "g");
"pattern matching .".replace(re, "regex");
yielding "pattern matching regex".
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('');
}
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;
Well if you are returning this function as a string, just use String#replace() method to replace x occurrence with its value.
This is how you should use it:
funcString.replace('x', x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
console.log(funcString.replace('x', x));
Edit:
If your variable has many occurrences and can be part of other variables just use a regex with replace method.
funcString.replace(/\bx\b/g, x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
let fix ='true';
let z = x * 2;
return y;
}.toString();
console.log(funcString.replace(/\bx\b/g, x));
use replace with regex, g will search all x-es
let x = Math.random();
let funcString = function () {
let y = x + 10;
let a = x + 10;
let b = x + 10;
return y;
}.toString().replace(/x/g, x);
console.log(funcString);
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)
First, the replace function returns a string, it does not mutate the variable. So, proper usage is as follows:
source = source.replace('old', 'new');
You should take care to ensure that your input is in the exact format, because if there is no trailing comma after the last value, and you want to replace the last value, then simply using replace would fail.
Replace all instances of element followed by an optional comma:
str = str.replace(new RegExp(element + ",?", "g"), "")
Your string appears to be delimited, so this is also an option:
var str = "#sport,#fotogallery,#sport,";
var element = "#sport";
var newStr = str.split(",").filter(function(el) {
return el !== element;
}).join(",");
Or, if you can't use filter, this will work, too:
var parts = str.split(",");
var res = [];
for (var i = 0; i < parts.length; i++) {
if (parts[i] !== element)
res.push(parts[i]);
}
var newStr = res.join(",");
This seems to work without needing look-behinds or look-aheads:
let regExMonth = /\bmonths\b/gm;
let str = "months + 3 + (startmonths * 3) + months - (months*7) + (monthsend*5)";
str = str.replace(regExMonth, "12");
console.log(str);
Screenshot from regexr.com:

You're right that the look-behinds don't work everywhere yet. However, they do work in Chrome, and they'll be working in Firefox soon. Look-behinds were added in the 2018 specification, so it is shameful that they are not yet ubiquitous here in 2020.
Where look-behinds are supported, I'd use a both a "negative look-behind" and a "negative look-ahead" too like this:
(?<![A-Za-z0-9_])(months)(?![A-Za-z0-9_])
Shorthand of above would be:
(?<![\w])(months)(?![\w])
Screenshot from regexr.com:

you can use negative look-ahead and look-behind at the same time
const regex = /(?<![\w+])(months)(?![\w+])/gm;
const str = `months + 3 + (startmonths * 3) + months - (months*7) + (monthsend*5)`;
const subst = `12`;
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);