I have a string with say: My Name is %NAME% and my age is %AGE%.

%XXX% are placeholders. We need to substitute values there from an object.

Object looks like: {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"}

I need to parse the object and replace the string with corresponding values. So that final output will be:

My Name is Mike and my age is 26.

The whole thing has to be done either using pure javascript or jquery.

推荐答案

The requirements of the original question clearly couldn't benefit from string interpolation, as it seems like it's a runtime processing of arbitrary replacement keys.

However, if you just had to do string interpolation, you can use:

const str = `My name is ${replacements.name} and my age is ${replacements.age}.`

Note the backticks delimiting the string, they are required.


For an answer suiting the particular OP's requirement, you could use String.prototype.replace() for the replacements.

The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).

var replacements = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"},
    str = 'My Name is %NAME% and my age is %AGE%.';

str = str.replace(/%\w+%/g, function(all) {
   return replacements[all] || all;
});

jsFiddle.

If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the in operator to achieve this.

jsFiddle.

However, if your format doesn't have a special format, i.e. any string, and your replacements object doesn't have a null prototype, use Object.prototype.hasOwnProperty(), unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.

jsFiddle.

Otherwise, if your replacement string was 'hasOwnProperty', you would get a resultant messed up string.

jsFiddle.


As a side note, you should be called replacements an Object, not an Array.

Jquery相关问答推荐

在 Laravel 中使用 jQuery post 按相关值过滤 Select 选项,如何显示从控制器返回的数据?

document.querySelector 一个元素中的多个数据属性

我如何从 ACE 编辑器中获得价值?

错误找不到 jquery-2.0.2.min.map

当有多个具有相同 ID 值的元素时,jQuery 是如何工作的?

用 jQuery 模拟按键

jQuery 序列化不注册复选框

如何使用 jquery 正确格式化货币?

jQuery $.cookie 不是一个函数

使用 jQuery 拖放防止单击事件

使用 jQuery 将宽度设置为百分比

jQuery '如果 .change() 或 .keyup()'

如何在javascript中获取json键和值?

Bootstrap 折叠动画不流畅

!!~(不是波浪号/bang bang 波浪号)如何改变包含/包含数组方法调用的结果?

当 iframe 在 jQuery 中完成加载时,如何触发事件?

查找 id 以开头的 html 元素

Select jQuery UI 自动完成后清除表单字段

JavaScript 中的简单节流阀

jQuery,简单的轮询示例