如何将变量放在javascript字符串中? (Node.js的)

时间:2011-10-17 07:53:18

标签: javascript string node.js

s = 'hello %s, how are you doing' % (my_name)

这就是你在python中的表现。你怎么能在javascript / node.js中做到这一点?

13 个答案:

答案 0 :(得分:315)

使用Node.js v4,您可以使用ES6' Template strings

var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing

你需要在反引号`中包裹字符串  而不是'

答案 1 :(得分:39)

如果你想要有类似的东西,可以创建一个函数:

function parse(str) {
    var args = [].slice.call(arguments, 1),
        i = 0;

    return str.replace(/%s/g, () => args[i++]);
}

用法:

s = parse('hello %s, how are you doing', my_name);

这只是一个简单的示例,并未考虑不同类型的数据类型(如%i等)或%s的转义。但我希望它能给你一些想法。我很确定还有一些库提供了这样的功能。

答案 2 :(得分:37)

util.format这样做。

它将成为v0.5.3的一部分,可以像这样使用:

var uri = util.format('http%s://%s%s', 
      (useSSL?'s':''), apiBase, path||'/');

答案 3 :(得分:33)

node.js >4.0开始,它与ES6标准更加兼容,其中字符串操作得到了极大的改进。

原始问题的回答可以简单如下:

var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '

在字符串可以分布多行的情况下,它使模板或HTML / XML过程变得非常容易。关于它的更多细节和更多功能:Template literals are string literals在mozilla.org。

答案 4 :(得分:21)

如果您使用的是ES6,则应使用模板文字。

//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`

在这里阅读更多内容: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

答案 5 :(得分:11)

那样做

s = 'hello ' + my_name + ', how are you doing'

答案 6 :(得分:4)

试试sprintf in JS  或者您可以使用此gist

答案 7 :(得分:4)

扩展String.prototype或使用ES2015 template literals的几种方法。

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 $1, $2'.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 $1, $2'.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>

答案 8 :(得分:3)

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)

答案 9 :(得分:2)

如果您使用的是node.js,console.log()将格式字符串作为第一个参数:

 console.log('count: %d', count);

答案 10 :(得分:1)

var user = "your name";
var s = 'hello ' + user + ', how are you doing';

答案 11 :(得分:1)

我写了function来精确解决问题。

第一个参数是要参数化的字符串。您应该将变量以这种格式“%s1,%s2,...%s12” 放在此字符串中。

其他参数分别是该字符串的参数。

/***
 * @example parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
 * @return "my name is John and surname is Doe"
 *
 * @firstArgument {String} like "my name is %s1 and surname is %s2"
 * @otherArguments {String | Number}
 * @returns {String}
 */
const parameterizedString = (...args) => {
  const str = args[0];
  const params = args.filter((arg, index) => index !== 0);
  if (!str) return "";
  return str.replace(/%s[0-9]+/g, matchedStr => {
    const variableIndex = matchedStr.replace("%s", "") - 1;
    return params[variableIndex];
  });
}

示例

parameterizedString("my name is %s1 and surname is %s2", "John", "Doe");
// returns "my name is John and surname is Doe"

parameterizedString("this%s1 %s2 %s3", " method", "sooo", "goood");
// returns "this method sooo goood"

如果该字符串中的变量位置发生变化,则此函数也支持它,而无需更改函数参数。

parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."

答案 12 :(得分:0)

这是Node.js中的多行字符串文字示例。

> let name = 'Fred'
> tm = `Dear ${name},
... This is to inform you, ${name}, that you are
... IN VIOLATION of Penal Code 64.302-4.
... Surrender yourself IMMEDIATELY!
... THIS MEANS YOU, ${name}!!!
...
... `
'Dear Fred,\nThis is to inform you, Fred, that you are\nIN VIOLATION of Penal Code 64.302-4.\nSurrender yourself IMMEDIATELY!\nTHIS MEANS YOU, Fred!!!\n\n'
console.log(tm)
Dear Fred,
This is to inform you, Fred, that you are
IN VIOLATION of Penal Code 64.302-4.
Surrender yourself IMMEDIATELY!
THIS MEANS YOU, Fred!!!


undefined
>