Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: string's format is not defined

Tags:

javascript

I have following snippet of javascript code:

var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));

getting following error:

Uncaught TypeError: undefined is not a function

what am i missing, here ?

like image 500
navyad Avatar asked Aug 10 '14 09:08

navyad


People also ask

How do you format a string in JavaScript?

JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on.

Is there a string format in TypeScript?

TypeScript doesn't add to the native objects, so it also doesn't have a String. format function.

What is format function in JS?

format() The format() method returns a string with a language-specific representation of the list.

What is printf in JavaScript?

Format in JavaScript. printf is a function that we use in most programming languages like C , PHP , and Java . This standard output function allows you to print a string or a statement on the console.23-Dec-2021.


1 Answers

String.format is not a native String extension. It's pretty easy to extend it yourself:

if (!String.prototype.format) {
  String.prototype.format = function(...args) {
    return this.replace(/(\{\d+\})/g, function(a) {
      return args[+(a.substr(1, a.length - 2)) || 0];
    });
  };
}
// usage
console.log("{0} world".format("hello"));
.as-console-wrapper { top: 0; max-height: 100% !important; }

[Update 2020]

It's not that fashionable anymore to extend native objects. Although I don't oppose it (if used carefully) a format-function can do exactly the same, or you can use es20xx template literals (see MDN).

// no native String extension
const someValue = 100;
const otherValue = 555;
const format = (str2Format, ...args) => 
  str2Format.replace(/(\{\d+\})/g, a => args[+(a.substr(1, a.length - 2)) || 0] );
console.log(format("someValue = {0}, otherValue = {1}", someValue, otherValue));

// template literal
console.log(`someValue = ${someValue}, otherValue = ${otherValue}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }
like image 180
KooiInc Avatar answered Oct 01 '22 15:10

KooiInc