JavaScript Equivalent to Printf/String.Format

JavaScript equivalent to printf/String.Format

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!

See Kim's answer below for details.



Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneously replacement instead like in fearphage’s suggestion.

JavaScript equivalent to printf/String.Format

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!

See Kim's answer below for details.



Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneously replacement instead like in fearphage’s suggestion.

equivalent of printf in javascript?

To combine literal strings with variables, you can concatenate them with the + operator.

loremipsum = 'Ambulatory Blood Pressure Report\nPatient name:' + patientname;

And just to be sure that I address the question in the title,

  • there's no built-in facility that provides the same formatting functionality as printf
  • there's no one "standard out" in JavaScript, so displaying text is different depending on how you want it to show up

(this is assuming the JavaScript is for a browser)

Use of String.Format in JavaScript?

Adapt the code from MsAjax string.

Just remove all of the _validateParams code and you are most of the way to a full fledged .NET string class in JavaScript.

Okay, I liberated the msajax string class, removing all the msajax dependencies. It Works great, just like the .NET string class, including trim functions, endsWith/startsWith, etc.

P.S. - I left all of the Visual Studio JavaScript IntelliSense helpers and XmlDocs in place. They are innocuous if you don't use Visual Studio, but you can remove them if you like.

<script src="script/string.js" type="text/javascript"></script>
<script type="text/javascript">
var a = String.format("Hello {0}!", "world");
alert(a);

</script>

String.js

// String.js - liberated from MicrosoftAjax.js on 03/28/10 by Sky Sanders
// permalink: http://stackoverflow.com/a/2534834/2343

/*
Copyright (c) 2009, CodePlex Foundation
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of CodePlex Foundation nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</textarea>
*/

(function(window) {

$type = String;
$type.__typeName = 'String';
$type.__class = true;

$prototype = $type.prototype;
$prototype.endsWith = function String$endsWith(suffix) {
/// <summary>Determines whether the end of this instance matches the specified string.</summary>
/// <param name="suffix" type="String">A string to compare to.</param>
/// <returns type="Boolean">true if suffix matches the end of this instance; otherwise, false.</returns>
return (this.substr(this.length - suffix.length) === suffix);
}

$prototype.startsWith = function String$startsWith(prefix) {
/// <summary >Determines whether the beginning of this instance matches the specified string.</summary>
/// <param name="prefix" type="String">The String to compare.</param>
/// <returns type="Boolean">true if prefix matches the beginning of this string; otherwise, false.</returns>
return (this.substr(0, prefix.length) === prefix);
}

$prototype.trim = function String$trim() {
/// <summary >Removes all leading and trailing white-space characters from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the start and end of the current String object.</returns>
return this.replace(/^\s+|\s+$/g, '');
}

$prototype.trimEnd = function String$trimEnd() {
/// <summary >Removes all trailing white spaces from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the end of the current String object.</returns>
return this.replace(/\s+$/, '');
}

$prototype.trimStart = function String$trimStart() {
/// <summary >Removes all leading white spaces from the current String object.</summary>
/// <returns type="String">The string that remains after all white-space characters are removed from the start of the current String object.</returns>
return this.replace(/^\s+/, '');
}

$type.format = function String$format(format, args) {
/// <summary>Replaces the format items in a specified String with the text equivalents of the values of corresponding object instances. The invariant culture will be used to format dates and numbers.</summary>
/// <param name="format" type="String">A format string.</param>
/// <param name="args" parameterArray="true" mayBeNull="true">The objects to format.</param>
/// <returns type="String">A copy of format in which the format items have been replaced by the string equivalent of the corresponding instances of object arguments.</returns>
return String._toFormattedString(false, arguments);
}

$type._toFormattedString = function String$_toFormattedString(useLocale, args) {
var result = '';
var format = args[0];

for (var i = 0; ; ) {
// Find the next opening or closing brace
var open = format.indexOf('{', i);
var close = format.indexOf('}', i);
if ((open < 0) && (close < 0)) {
// Not found: copy the end of the string and break
result += format.slice(i);
break;
}
if ((close > 0) && ((close < open) || (open < 0))) {

if (format.charAt(close + 1) !== '}') {
throw new Error('format stringFormatBraceMismatch');
}

result += format.slice(i, close + 1);
i = close + 2;
continue;
}

// Copy the string before the brace
result += format.slice(i, open);
i = open + 1;

// Check for double braces (which display as one and are not arguments)
if (format.charAt(i) === '{') {
result += '{';
i++;
continue;
}

if (close < 0) throw new Error('format stringFormatBraceMismatch');

// Find the closing brace

// Get the string between the braces, and split it around the ':' (if any)
var brace = format.substring(i, close);
var colonIndex = brace.indexOf(':');
var argNumber = parseInt((colonIndex < 0) ? brace : brace.substring(0, colonIndex), 10) + 1;

if (isNaN(argNumber)) throw new Error('format stringFormatInvalid');

var argFormat = (colonIndex < 0) ? '' : brace.substring(colonIndex + 1);

var arg = args[argNumber];
if (typeof (arg) === "undefined" || arg === null) {
arg = '';
}

// If it has a toFormattedString method, call it. Otherwise, call toString()
if (arg.toFormattedString) {
result += arg.toFormattedString(argFormat);
}
else if (useLocale && arg.localeFormat) {
result += arg.localeFormat(argFormat);
}
else if (arg.format) {
result += arg.format(argFormat);
}
else
result += arg.toString();

i = close + 1;
}

return result;
}

})(window);

sprintf equivalent for client-side JavaScript

Keep it simple

var sprintf = (str, ...argv) => !argv.length ? str : 
sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);

Since Javascript handles data types automatically, there is no need for type options.

If you need padding, "15".padStart(5,"0") = ("00000"+15).slice(-5) = "00015".

Usage

var sprintf = (str, ...argv) => !argv.length ? str : 
sprintf(str = str.replace(sprintf.token||"$", argv.shift()), ...argv);

alert(sprintf("Success after $ clicks ($ seconds).", 15, 4.569));
sprintf.token = "_";
alert(sprintf("Failure after _ clicks (_ seconds).", 5, 1.569));

sprintf.token = "%";
var a = "%<br>%<br>%";
var b = sprintf("% plus % is %", 0, 1, 0 + 1);
var c = sprintf("Hello, %!", "world");
var d = sprintf("The answer to everything is %.", 42);
document.write(sprintf(a,b,c,d));

Javascript equivalent to python's .format()

UPDATE: If you're using ES6, template strings work very similarly to String.format: https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

If not, the below works for all the cases above, with a very similar syntax to python's String.format method. Test cases below.

String.prototype.format = function() {

var args = arguments;

this.unkeyed_index = 0;

return this.replace(/\{(\w*)\}/g, function(match, key) {

if (key === '') {

key = this.unkeyed_index;

this.unkeyed_index++

}

if (key == +key) {

return args[key] !== 'undefined'

? args[key]

: match;

} else {

for (var i = 0; i < args.length; i++) {

if (typeof args[i] === 'object' && typeof args[i][key] !== 'undefined') {

return args[i][key];

}

}

return match;

}

}.bind(this));

};

// Run some tests

$('#tests')

.append(

"hello {} and {}<br />".format("you", "bob")

)

.append(

"hello {0} and {1}<br />".format("you", "bob")

)

.append(

"hello {0} and {1} and {a}<br />".format("you", "bob", {a:"mary"})

)

.append(

"hello {0} and {1} and {a} and {2}<br />".format("you", "bob", "jill", {a:"mary"})

);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="tests"></div>

Is there a elegant javascript equivalent of this python code using formatting?

You could replace by shifting the array values.

const
format = (pattern, [...array]) =>
pattern.replace(/\{\}/g, Array.prototype.shift.bind(array));

console.log(format('{}{}{} {}{}{}-{}{}{}{}', [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));


Related Topics



Leave a reply



Submit