I want to write a function to replace variables in a string with actual values, for example:
function replaceUrl(url, data) {}
The caller may be:
replaceUrl('/task/:module?taskId=:taskId#:hash', {
module: 'm1',
taskId: 't1',
hash: 'h1'
});
I think to use RegEx may be simple to implement this, but I'm not very familiar with it.
Can anyone provide a simple way on this?
You use the replace() method by: assigning the initial string or strings to a variable. declaring another variable. for the value of the new variable, prepending the new variable name with the replace() method.
replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
A placeholder is represented by ${} , with anything within the curly brackets treated as JavaScript and anything outside the brackets treated as a string: const method = 'interpolation' const dynamicString = `This string is using ${method}.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With