最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - JavaScript to replace variable in a string - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited May 3, 2016 at 3:36 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked May 3, 2016 at 2:57 LuneLune 3511 gold badge3 silver badges13 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 17

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/

You can use the form of String.prototype.replace that takes a function as an argument.

Using your example this could look like:

var str = '/task/:module?taskId=:taskId#:hash&:missing';
var obj = {
    module: 'm1',
    taskId: 't1',
    hash: 'h1'
};

function replaceUrl(url, data) {
    var regex = /:(\w+)/g;
    return url.replace(regex, function(match, p1) {
        return data[p1] || ':' + p1;
    });
}

replaceUrl(str, obj); // /task/m1?taskId=t1#h1&:missing

This method will handle all parameters you pass values in for and ignore ones that are missing.

I wrote a simple JavaScript function called stringInject to solve this exact problem I was having. It would allow you to do the following. Find links to the code below.

var str = "This is a {0} string for {1}"
var newStr = stringInject(str, ["test", "stringInject"]);

// This is a test string for stringInject 

NPM / GitHub links:

https://www.npmjs.com/package/stringinject

https://github.com/tjcafferkey/stringinject

The Function

function stringInject(str, arr) {
    if (typeof str !== 'string' || !(arr instanceof Array)) {
        return false;
    }

    return str.replace(/({\d})/g, function(i) {
        return arr[i.replace(/{/, '').replace(/}/, '')];
    });
}

You can use the following function

function replaceStringVariable(text, data) {
  // Create regex using the keys of the replacement object.
  const regex = new RegExp('\\${(' + Object.keys(data).join('|') + ')}', 'g')
  
  // Replace the string by the value in object
  return text.replace(regex, (m, p1) => data[p1] || m)
}

const newText = replaceStringVariable('hello ${name} and ${nameTwo}', {
  name: "Pedro",
  nameTwo: "Juan"
})

console.log('newText', newText)

发布评论

评论列表(0)

  1. 暂无评论