Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to replace variable in a string

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?

like image 668
Lune Avatar asked May 03 '16 02:05

Lune


People also ask

How do you replace a variable in a string?

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.

How do you replace a certain part of a string JavaScript?

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.

What is replace () in JavaScript?

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.

What is this ${} in JavaScript?

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}.


1 Answers

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;
like image 156
Tushar Avatar answered Sep 20 '22 21:09

Tushar