[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. How can you do that in javascript/node.js?

This question is related to javascript string node.js

The answer is


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 '


If you are using node.js, console.log() takes format string as a first parameter:

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

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.


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".

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."

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

_x000D_
_x000D_
const format = (...args) => args.shift().replace(/%([jsd])/g, x => x === '%j' ? JSON.stringify(args.shift()) : args.shift())_x000D_
_x000D_
const name = 'Csaba'_x000D_
const formatted = format('Hi %s, today is %s and your data is %j', name, Date(), {data: {country: 'Hungary', city: 'Budapest'}})_x000D_
_x000D_
console.log(formatted)
_x000D_
_x000D_
_x000D_


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
>

Try sprintf in JS or you could use this gist


Do that:

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

Update

With ES6, you could also do this:

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

util.format does this.

It will be part of v0.5.3 and can be used like this:

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

if you are using ES6, the you should use the Template literals.

//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


A few ways to extend String.prototype, or use ES2015 template literals.

_x000D_
_x000D_
var result = document.querySelector('#result');_x000D_
// -----------------------------------------------------------------------------------_x000D_
// Classic_x000D_
String.prototype.format = String.prototype.format ||_x000D_
  function () {_x000D_
    var args = Array.prototype.slice.call(arguments);_x000D_
    var replacer = function (a){return args[a.substr(1)-1];};_x000D_
    return this.replace(/(\$\d+)/gm, replacer)_x000D_
};_x000D_
result.textContent = _x000D_
  'hello $1, $2'.format('[world]', '[how are you?]');_x000D_
_x000D_
// ES2015#1_x000D_
'use strict'_x000D_
String.prototype.format2 = String.prototype.format2 ||_x000D_
  function(...merge) { return this.replace(/\$\d+/g, r => merge[r.slice(1)-1]); };_x000D_
result.textContent += '\nHi there $1, $2'.format2('[sir]', '[I\'m fine, thnx]');_x000D_
_x000D_
// ES2015#2: template literal_x000D_
var merge = ['[good]', '[know]'];_x000D_
result.textContent += `\nOk, ${merge[0]} to ${merge[1]}`;
_x000D_
<pre id="result"></pre>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`