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

%XXX%是占位符.我们需要替换一个对象的值.

物体看起来像:{"%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:

我叫迈克,今年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,如果你只需要做字符串插值,你可以使用:

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.

如果某些替换项不是字符串,请确保它们首先存在于对象中.如果您有类似示例的格式,即用百分号括起来,则可以使用in运算符来实现这一点.

jsFiddle.

但是,如果您的格式没有特殊的格式,即任何字符串,并且您的replacements对象没有null原型,请使用Object.prototype.hasOwnProperty(),除非您可以保证任何可能替换的子字符串都不会与原型上的属性名称冲突.

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相关问答推荐

jQueryUI 模态对话框不显示关闭按钮 (x)

jQuery单击/切换两个功能

JQuery通过类名获取所有元素

在 for 循环中分配点击处理程序

如何在 jquery 中从这个日期减go 一周?

jQuery:获取所选单选按钮的父 tr

Facebook 风格的 JQuery 自动完成插件

Google Maps API v3 infowindow 关闭事件/回调?

一次替换多个字符串

如何使用给定的 url 判断图像是否存在?

如何同时使用 requireJS 和 jQuery?

我可以使用 jQuery 打开下拉列表吗

使用 MVC、C# 和 jQuery 导出为 CSV

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

如何使用 jquery 动态更改 iframe 中的内容?

带有 jQ​​uery 的饼图

jQuery 按值 Select 选项元素

javascript jquery单选按钮单击

jQuery: Select 不为空的数据属性?

如何使用 jquery 更改元素类型