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?
As of node.js
>4.0
it gets more compatible with ES6 standard, where string manipulation greatly improved.
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. More details and more capabilitie about it: Template literals are string literals at mozilla.org.
If you are using node.js, console.log() takes format string as a first parameter:
console.log('count: %d', count);
Here is a Multi-line String Literal example 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
>
With Node.js v4
, you can use ES6's 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
You need to wrap string within backtick `
instead of '
A few ways to extend String.prototype
, or use 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>
var user = "your name";
var s = 'hello ' + user + ', how are you doing';