Javascript: string format not defined

I have the following javascript code snippet:

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

get the following error:

 Uncaught TypeError: undefined is not a function 

What am I missing here?

+4
javascript
Aug 10 '14 at 9:07
source share
2 answers

String.format not a native extension of String . It is quite easy to expand it:

 String.prototype.format = function () { var args = [].slice.call(arguments); return this.replace(/(\{\d+\})/g, function (a){ return args[+(a.substr(1,a.length-2))||0]; }); }; // usage '{0} world'.format('hello'); //=> 'hello world' 
+11
Aug 10 '14 at 9:13
source share
 String.format = function() { var s = arguments[0]; for (var i = 0; i < arguments.length - 1; i += 1) { var reg = new RegExp('\\{' + i + '\\}', 'gm'); s = s.replace(reg, arguments[i + 1]); } return s; }; var strTempleate = String.format('hello {0}', 'Ortal'); 
+3
May 2 '16 at 11:18
source share



All Articles