You can take advantage of Template Literals and use this syntax:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
This feature has been introduced in ES2015 (ES6).
Example
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
How neat is that?
Bonus:
It also allows for multi-line strings in javascript without escaping, which is great for templates:
return `
<div class="${foo}">
...
</div>
`;
Browser support:
As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.
Side note:
Starting from IE8+ you can use basic string formatting inside console.log:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
Answer from bformet on Stack OverflowYou can take advantage of Template Literals and use this syntax:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
This feature has been introduced in ES2015 (ES6).
Example
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
How neat is that?
Bonus:
It also allows for multi-line strings in javascript without escaping, which is great for templates:
return `
<div class="${foo}">
...
</div>
`;
Browser support:
As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.
Side note:
Starting from IE8+ you can use basic string formatting inside console.log:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, nope, that was not possible in javascript. You would have to resort to:
var hello = "foo";
var my_string = "I pity the " + hello;
It's 2017, we have template literals.
var name = "javascript";
console.log(`My name is ${name}`);
// My name is javascript
It uses back-tick not single quote.
You may find this question and answers also useful. JavaScript equivalent to printf/string.format
There's no native way to do that. In javascript, you do:
var name = 'javascript';
var a = 'My name is ' + name;
console.log(a);
>>>My name is javascript
Otherwise, if you really would like to use a string formatter, you could use a library. For example, https://github.com/alexei/sprintf.js
With sprintf library:
var name = 'javascript';
sprintf('My name is %s', name);
>>>My name is javascript
The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.
However, if you just had to do string interpolation, you can use:
const str = `My name is ${replacements.name} and my age is ${replacements.age}.`
Note the backticks delimiting the string, they are required.
For an answer suiting the particular OP's requirement, you could use String.prototype.replace() for the replacements.
The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).
var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
str = 'My Name is %NAME% and my age is %AGE%.';
str = str.replace(/%\w+%/g, function(all) {
return replacements[all] || all;
});
jsFiddle.
If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in operator to achieve this.
jsFiddle.
However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null prototype, use Object.prototype.hasOwnProperty(), unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.
jsFiddle.
Otherwise, if your replacement string was 'hasOwnProperty', you would get a resultant messed up string.
jsFiddle.
As a side note, you should be called replacements an Object, not an Array.
How about using ES6 template literals?
var a = "cat";
var b = "fat";
console.log(`my ${a} is ${b}`); //notice back-ticked string
More about template literals...
Aren't you just missing a return here?
function processRepVar(rvName) {
var data = getRepVarData(rvName);
if(data.indexOf('$$') > -1) {
subText(data);
} else {
return data;
}
}
Changing subText(data) to return subText(data); makes your code work for me.
Working jsfiddle: https://jsfiddle.net/uzxno754/
Have you tried regular expressions for this?
function replace(str, data) {
let re = /\$\$(\w+)\$\$/g;
while (re.test(str))
str = str.replace(re, (_, w) => data[w]);
return str;
}
//
var exampleText = "A string with variables $$cr$$";
var repvars = {
cr: 'Copyright for this is $$year$$',
year: '2019'
}
console.log(replace(exampleText, repvars))
Basically, this repeatedly replaces $$...$$ things in a string until there are no more.
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/