如何将变量放在javascript字符串中?

2020/11/12 16:23 · javascript ·  · 0评论
s = 'hello %s, how are you doing' % (my_name)

这就是您在python中执行的方式。您如何在javascript / node.js中做到这一点?

请注意,从2015年起,只需使用反引号进行模板

https://stackoverflow.com/a/372​​45773/294884

let a = `hello ${name}`    // NOTE!!!!!!!! ` not ' or "

请注意,这是反引号,而不是引号。


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

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但我希望它能给您一些想法。我很确定那里也有提供这样功能的库。

通过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

您需要将字符串包装在反引号内,`
而不是
'

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

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

在此处阅读更多信息:https :
//developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Template_literals

截至目前,node.js >4.0它与ES6标准更加兼容,该标准极大地改善了字符串操作。

原始问题答案可以很简单:

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

在字符串可以散布多行的地方,它使模板或HTML / XML处理变得非常容易。更多细节和更多功能:模板文字是mozilla.org上的字符串文字

util.format执行此操作。

它是v0.5.3的一部分,可以这样使用:

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

去做:

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

更新资料

使用ES6,您还可以执行以下操作:

s = `hello ${my_name}, how are you doing`

扩展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 $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>

在JS中尝试sprintf
或可以使用此
要点

我写了一个函数来精确地解决问题。

第一个参数是要参数化的字符串。您应该将变量放在字符串中,例如“%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."

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

 console.log('count: %d', count);
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)
var user = "your name";
var s = 'hello ' + user + ', how are you doing';

这是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
>
本文地址:http://javascript.askforanswer.com/ruhejiangbianliangfangzaijavascriptzifuchuanzhong.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!