简体   繁体   English

JavaScript替换字符串中的变量

[英]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. 我认为使用RegEx可能很容易实现这一点,但我对它不是很熟悉。

Can anyone provide a simple way on this? 任何人都可以提供一个简单的方法吗?

A simple solution is not to use RegEx at all. 一个简单的解决方案是根本不使用RegEx。 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: 使用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: 您可以编写一个非常简单的模板函数来实现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/ 小提琴: https//jsfiddle.net/j5hp2cfv/

You can use the form of String.prototype.replace that takes a function as an argument . 您可以使用String.prototype.replace的形式, 它将函数作为参数

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. 我写了一个名为stringInject的简单JavaScript函数来解决我遇到的这个问题。 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: NPM / GitHub链接:

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

https://github.com/tjcafferkey/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(/}/, '')];
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM