使用占位符和替换对象格式化 JavaScript 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7975005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Format a JavaScript string using placeholders and an object of substitutions?
提问by Joby Joseph
I have a string with say: My Name is %NAME% and my age is %AGE%.
我有一个字符串说: My Name is %NAME% and my age is %AGE%.
%XXX%
are placeholders. We need to substitute values there from an object.
%XXX%
是占位符。我们需要从一个对象替换那里的值。
Object looks like: {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"}
对象看起来像: {"%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.
我的名字是迈克,我的年龄是 26 岁。
The whole thing has to be done either using pure javascript or jquery.
整个过程必须使用纯 javascript 或 jquery 来完成。
回答by alex
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.
对于适合特定 OP 要求的答案,您可以将其String.prototype.replace()
用于替换。
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;
});
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.
如果您的某些替换不是字符串,请首先确保它们存在于对象中。如果您有类似示例的格式,即用百分号包裹,您可以使用in
运算符来实现这一点。
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.
但是,如果您的格式没有特殊格式,即任何字符串,并且您的替换对象没有null
原型,请使用Object.prototype.hasOwnProperty()
,除非您可以保证您的潜在替换子字符串都不会与原型上的属性名称冲突。
Otherwise, if your replacement string was 'hasOwnProperty'
, you would get a resultant messed up string.
否则,如果您的替换字符串是'hasOwnProperty'
,您将得到一个混乱的字符串。
As a side note, you should be called replacements
an Object
, not an Array
.
作为旁注,您应该被称为replacements
an Object
,而不是 an Array
。
回答by Tomasz Mularczyk
How about using ES6 template literals?
使用 ES6 模板文字怎么样?
var a = "cat";
var b = "fat";
console.log(`my ${a} is ${b}`); //notice back-ticked string
回答by zawhtut
You can use JQuery(jquery.validate.js) to make it work easily.
您可以使用 JQuery(jquery.validate.js) 使其轻松工作。
$.validator.format("My name is {0}, I'm {1} years old",["Bob","23"]);
Or if you want to use just that feature you can define that function and just use it like
或者,如果您只想使用该功能,则可以定义该功能并像这样使用它
function format(source, params) {
$.each(params,function (i, n) {
source = source.replace(new RegExp("\{" + i + "\}", "g"), n);
})
return source;
}
alert(format("{0} is a {1}", ["Michael", "Guy"]));
credit to jquery.validate.js team
归功于 jquery.validate.js 团队
回答by Eric Wang
As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf()
.
与现代浏览器一样,新版本的 Chrome / Firefox 支持占位符,类似于 C 风格的功能printf()
。
Placeholders:
占位符:
%s
String.%d
,%i
Integer number.%f
Floating point number.%o
Object hyperlink.
%s
细绳。%d
,%i
整数。%f
浮点数。%o
对象超链接。
e.g.
例如
console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);
BTW, to see the output:
顺便说一句,要查看输出:
- In Chrome, use shortcut
Ctrl + Shift + J
orF12
to open developer tool. - In Firefox, use shortcut
Ctrl + Shift + K
orF12
to open developer tool.
- 在 Chrome 中,使用快捷方式
Ctrl + Shift + J
或F12
打开开发者工具。 - 在 Firefox 中,使用快捷方式
Ctrl + Shift + K
或F12
打开开发者工具。
@Update - nodejs support
@Update - nodejs 支持
Seems nodejs don't support %f
, instead, could use %d
in nodejs.
With %d
number will be printed as floating number, not just integer.
似乎 nodejs 不支持%f
,而是可以%d
在 nodejs 中使用。with %d
number 将打印为浮点数,而不仅仅是整数。
回答by hafichuk
回答by jfriend00
You can use a custom replace function like this:
您可以使用这样的自定义替换功能:
var str = "My Name is %NAME% and my age is %AGE%.";
var replaceData = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
function substitute(str, data) {
var output = str.replace(/%[^%]+%/g, function(match) {
if (match in data) {
return(data[match]);
} else {
return("");
}
});
return(output);
}
var output = substitute(str, replaceData);
You can see it work here: http://jsfiddle.net/jfriend00/DyCwk/.
你可以在这里看到它的工作:http: //jsfiddle.net/jfriend00/DyCwk/。
回答by loretoparisi
If you want to do something closer to console.log like replacing %s placeholders like in
如果你想做一些更接近 console.log 的事情,比如替换 %s 占位符,比如
>console.log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright")
>Hello Loreto how are you today is everything allright?
I wrote this
我写了这个
function log() {
var args = Array.prototype.slice.call(arguments);
var rep= args.slice(1, args.length);
var i=0;
var output = args[0].replace(/%s/g, function(match,idx) {
var subst=rep.slice(i, ++i);
return( subst );
});
return(output);
}
res=log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright");
document.getElementById("console").innerHTML=res;
<span id="console"/>
you will get
你会得到
>log("Hello %s how are you %s is everything %s?", "Loreto", "today", "allright")
>"Hello Loreto how are you today is everything allright?"
UPDATE
更新
I have added a simple variant as String.prototype
useful when dealing with string transformations, here is it:
我添加了一个String.prototype
在处理字符串转换时有用的简单变体,如下所示:
String.prototype.log = function() {
var args = Array.prototype.slice.call(arguments);
var rep= args.slice(0, args.length);
var i=0;
var output = this.replace(/%s|%d|%f|%@/g, function(match,idx) {
var subst=rep.slice(i, ++i);
return( subst );
});
return output;
}
In that case you will do
在这种情况下,你会做
"Hello %s how are you %s is everything %s?".log("Loreto", "today", "allright")
"Hello Loreto how are you today is everything allright?"
Try this version here
在这里试试这个版本
回答by tjcafferkey
This allows you to do exactly that
这使您可以完全做到这一点
NPM: https://www.npmjs.com/package/stringinject
NPM:https: //www.npmjs.com/package/stringinject
GitHub: https://github.com/tjcafferkey/stringinject
GitHub: https://github.com/tjcafferkey/stringinject
By doing the following:
通过执行以下操作:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
// My username is tjcafferkey on Git
回答by Simon Sch?rer
Here is another way of doing this by using es6 template literals dynamically at runtime.
这是通过在运行时动态使用 es6 模板文字来执行此操作的另一种方法。
const str = 'My name is ${name} and my age is ${age}.'
const obj = {name:'Simon', age:'33'}
const result = new Function('const {' + Object.keys(obj).join(',') + '} = this.obj;return `' + str + '`').call({obj})
document.body.innerHTML = result
回答by Yomi
As a quick example:
举个简单的例子:
var name = 'Hyman';
var age = 40;
console.log('%s is %d yrs old',name,age);
The output is:
输出是:
Hyman is 40 yrs old
Hyman 40 岁