You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation. The difference is, the interpolation example is much easier to read.
To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).
Add numbers in JavaScript by placing a plus sign between them. You can also use the following syntax to perform addition: var x+=y; The "+=" operator tells JavaScript to add the variable on the right side of the operator to the variable on the left.
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 '
Note, from 2015 onwards, just use backticks for templating
https://stackoverflow.com/a/37245773/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
. 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.
//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
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||'/');
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.
Do that:
s = 'hello ' + my_name + ', how are you doing'
With ES6, you could also do this:
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".
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With