简体   繁体   English

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

[英]How do I put variables inside javascript strings?

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

That's how you do it in python.这就是你在python中的做法。 How can you do that in javascript/node.js?你怎么能在 javascript/node.js 中做到这一点?

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 '您需要将字符串包裹在反引号`而不是'

Note, from 2015 onwards, just use backticks for templating请注意,从 2015 年开始,只需使用反引号进行模板化

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

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

Note that it is a backtick , not a quote.请注意,它是一个反引号,而不是引号。


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 .这只是一个简单的例子,并没有考虑不同类型的数据类型(如%i等)或转义%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.我很确定还有一些库可以提供这样的功能。

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

util.format does this. util.format 就是这样做的。

It will be part of v0.5.3 and can be used like this:它将成为v0.5.3 的一部分,可以像这样使用:

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

As of node.js >4.0 it gets more compatible with ES6 standard, where string manipulation greatly improved.node.js >4.0它与 ES6 标准更加兼容,其中字符串操作大大改进。

The answer to 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.在字符串可以分布多行的情况下,它使模板或 HTML/XML 处理变得非常容易。 More details and more capabilitie about it: Template literals are string literals at mozilla.org.关于它的更多细节和更多功能: 模板文字是mozilla.org 上的字符串文字

Do that:去做:

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

Update更新

With ES6, you could also do this:使用 ES6,你也可以这样做:

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

I wrote a function which solves the problem precisely.我写了一个函数来精确解决问题。

First argument is the string that wanted to be parameterized.第一个参数是要参数化的字符串。 You should put your variables in this string like this format "%s1, %s2, ... %s12" .你应该把你的变量放在这个字符串中,就像这样的格式"%s1, %s2, ... %s12"

Other arguments are the parameters respectively for that string.其他参数分别是该字符串的参数。

/***
 * @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];
  });
}

Examples例子

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"

If variable position changes in that string, this function supports it too without changing the function parameters.如果该字符串中的变量位置发生变化,该函数也支持它,而无需更改函数参数。

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

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 $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或者你可以使用这个要点

如果您使用 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';

Here is a Multi-line String Literal example in Node.js.这是 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
>
var print = console.log;

function dformat(str, ...arr) {
  return str.replace(/%(\d+)/g, function(_,i) {
    return arr[--i];
  });
}

function wformat(str, dict) {
  return str.replace(/%(\w+)/g, function(_,k) {
    return dict[k];
  });
}

function sformat(str, dict) {
  return str.replace(/\$(\w+)/g, function(_,m) {
    return dict[m];
  });
}

function tformat(str, dict) {
  return str.replace(/\${(\w+)}/g, function(_,m) {
    return dict[m];
  });
}

print(1, dformat("uid:%1, name:%2", 120, "someone") )
print(2, wformat("color: %name", {name: "green"})   )
print(3, sformat("img: $url", {url: "#"})   )
print(4, tformat("${left} ${right}", {right:"1000", left: "7fff"}) )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM