使用占位符和替换对象格式化JavaScript字符串? [英] Format a JavaScript string using placeholders and an object of substitutions?

查看:1048
本文介绍了使用占位符和替换对象格式化JavaScript字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,上面写着:我的名字是%NAME%,我的年龄是%AGE%。

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

%XXX%是占位符。我们需要从对象替换值。

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

对象看起来像: {%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岁。

My Name is Mike and my age is 26.

整个过程必须使用纯javascript或jquery来完成。

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}.`

注意分隔字符串的反引号,它们是必需的。

对于符合特定OP要求的答案,您可以使用 String.prototype.replace()进行替换。

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

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

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

否则,如果您的替换字符串是'hasOwnProperty',你会得到一个混乱的字符串。

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

jsFiddle

作为旁注,你应该被称为替换一个对象,n一个数组

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

这篇关于使用占位符和替换对象格式化JavaScript字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆