如何将变量放入 javascript 字符串中?(节点.js)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7790811/
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
How do I put variables inside javascript strings? (Node.js)
提问by TIMEX
s = 'hello %s, how are you doing' % (my_name)
That's how you do it in python. How can you do that in javascript/node.js?
这就是你在python中的做法。你怎么能在 javascript/node.js 中做到这一点?
采纳答案by Felix Kling
If you want to have something similar, you could create a function:
如果你想要类似的东西,你可以创建一个函数:
function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i++]);
}
Usage:
用法:
s = parse('hello %s, how are you doing', my_name);
This is only a simple example and does not take into account different kinds of data types (like %i
, etc) or escaping of %s
. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.
这只是一个简单的例子,并没有考虑不同类型的数据类型(如%i
等)或转义%s
. 但我希望它能给你一些想法。我很确定还有一些库可以提供这样的功能。
回答by Sridhar
With Node.js v4
, you can use ES6's Template strings
使用 Node.js v4
,您可以使用 ES6 的模板字符串
var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing
You need to wrap string within backtick `
instead of '
你需要用反引号包裹字符串`
而不是'
回答by Terrence
if you are using ES6, the you should use the Template literals.
如果您使用的是 ES6,则应该使用模板文字。
//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`
read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
在此处阅读更多信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
回答by Andrew_1510
As of node.js
>4.0
it gets more compatible with ES6 standard, where string manipulation greatly improved.
随着node.js
>4.0
它与 ES6 标准更加兼容,字符串操作大大改进。
The answerto the original question can be as simple as:
原始问题的答案可以很简单:
var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '
Where the string can spread multiple lines, it makes templates or HTML/XML processes quite easy. More details and more capabilitie about it: Template literals are string literalsat mozilla.org.
在字符串可以扩展多行的情况下,它使模板或 HTML/XML 处理变得非常容易。关于它的更多细节和更多功能:模板文字是mozilla.org上的字符串文字。
回答by Jim Schubert
util.formatdoes this.
util.format 就是这样做的。
It will be part of v0.5.3and can be used like this:
它将成为v0.5.3 的一部分,可以像这样使用:
var uri = util.format('http%s://%s%s',
(useSSL?'s':''), apiBase, path||'/');
回答by Merianos Nikos
Do that
去做
s = 'hello ' + my_name + ', how are you doing'
回答by KooiInc
A few ways to extend String.prototype
, or use ES2015 template literals.
几种扩展String.prototype
或使用 ES2015模板文字的方法。
var result = document.querySelector('#result');
// -----------------------------------------------------------------------------------
// Classic
String.prototype.format = String.prototype.format ||
function () {
var args = Array.prototype.slice.call(arguments);
var replacer = function (a){return args[a.substr(1)-1];};
return this.replace(/($\d+)/gm, replacer)
};
result.textContent =
'hello , '.format('[world]', '[how are you?]');
// ES2015#1
'use strict'
String.prototype.format2 = String.prototype.format2 ||
function(...merge) { return this.replace(/$\d+/g, r => merge[r.slice(1)-1]); };
result.textContent += '\nHi there , '.format2('[sir]', '[I\'m fine, thnx]');
// ES2015#2: template literal
var merge = ['[good]', '[know]'];
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
<pre id="result"></pre>
回答by spicavigo
Try sprintf in JSor you could use this gist
回答by cstuncsik
const format = (...args) => args.shift().replace(/%([jsd])/g, x => x === '%j' ? JSON.stringify(args.shift()) : args.shift())
const name = 'Csaba'
const formatted = format('Hi %s, today is %s and your data is %j', name, Date(), {data: {country: 'Hungary', city: 'Budapest'}})
console.log(formatted)
回答by Andrey Sidorov
If you are using node.js, console.log()takes format string as a first parameter:
如果您使用 node.js,console.log()将格式字符串作为第一个参数:
console.log('count: %d', count);