s = 'hello %s, how are you doing' % (my_name)
Ecco come lo fai in Python. Come puoi farlo in javascript / node.js?
s = 'hello %s, how are you doing' % (my_name)
Ecco come lo fai in Python. Come puoi farlo in javascript / node.js?
Risposte:
Se vuoi avere qualcosa di simile, puoi creare una funzione:
function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i++]);
}
Uso:
s = parse('hello %s, how are you doing', my_name);
Questo è solo un semplice esempio e non tiene conto di diversi tipi di tipi di dati (come %i, ecc.) O di escape %s. Ma spero che ti dia qualche idea. Sono abbastanza sicuro che ci siano anche librerie là fuori che forniscono una funzione come questa.
Con Node.js v4è possibile utilizzare le stringhe modello di ES6
var my_name = 'John';
var s = `hello ${my_name}, how are you doing`;
console.log(s); // prints hello John, how are you doing
È necessario avvolgere la stringa all'interno del backtick `
anziché'
hello ${my_name}, how are you doinge desidero assegnare la variabile in modo dinamico dopo aver letto la stringa dalla configurazione?
se stai usando ES6, dovresti usare i letterali Template.
//you can do this
let sentence = `My name is ${ user.name }. Nice to meet you.`
leggi di più qui: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
A partire da node.js >4.0quando diventa più compatibile con lo standard ES6, dove la manipolazione delle stringhe è notevolmente migliorata.
La risposta alla domanda originale può essere semplice come:
var s = `hello ${my_name}, how are you doing`;
// note: tilt ` instead of single quote '
Laddove la stringa può diffondere più righe, rende piuttosto semplici modelli o processi HTML / XML. Maggiori dettagli e maggiori capacità al riguardo: i letterali template sono letterali stringa su mozilla.org.
util.format fa questo.
Farà parte di v0.5.3 e può essere utilizzato in questo modo:
var uri = util.format('http%s://%s%s',
(useSSL?'s':''), apiBase, path||'/');
Fai quello:
s = 'hello ' + my_name + ', how are you doing'
Con ES6, puoi anche fare questo:
s = `hello ${my_name}, how are you doing`
Alcuni modi per estendere String.prototypeo utilizzare i letterali modello 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>
Prova sprintf in JS o potresti usare questa sintesi
Se si utilizza node.js, console.log () accetta la stringa di formato come primo parametro:
console.log('count: %d', count);
console.log()genera solo la stringa formattata in STDOUT. In altre parole, non puoi usare il risultato dicount: %d
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)
Ho scritto una funzione che risolve esattamente il problema.
Il primo argomento è la stringa che voleva essere parametrizzata. Dovresti inserire le tue variabili in questa stringa come questo formato "% s1,% s2, ...% s12" .
Altri argomenti sono i parametri rispettivamente per quella stringa.
/***
* @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];
});
}
Esempi
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"
Se la posizione variabile cambia in quella stringa, anche questa funzione la supporta senza modificare i parametri della funzione.
parameterizedString("i have %s2 %s1 and %s4 %s3.", "books", 5, "pencils", "6");
// returns "i have 5 books and 6 pencils."
var user = "your name";
var s = 'hello ' + user + ', how are you doing';
Ecco un esempio letterale di stringa multilinea in 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 s = 'hello ${my_name}, how are you doing';