javascriptregex

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?


Solution

  • 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;