Javascript equivalent to python's .format()
Asked Answered
S

2

10

I would like a javascript function that mimics the python .format() function that works like

.format(*args, **kwargs)

A previous question gives a possible (but not complete) solution for '.format(*args)

JavaScript equivalent to printf/string.format

I would like to be able to do

"hello {} and {}".format("you", "bob"
==> hello you and bob

"hello {0} and {1}".format("you", "bob")
==> hello you and bob

"hello {0} and {1} and {a}".format("you", "bob",a="mary")
==> hello you and bob and mary

"hello {0} and {1} and {a} and {2}".format("you", "bob","jill",a="mary")
==> hello you and bob and mary and jill

I realize that's a tall order, but maybe somewhere out there is a complete (or at least partial) solution that includes keyword arguments as well.

Oh, and I hear AJAX and JQuery possibly have methods for this, but I would like to be able to do it without all that overhead.

In particular, I would like to be able to use it with a script for a google doc.

Thanks

Sansone answered 30/11, 2012 at 5:18 Comment(4)
Hmm interested about the answer of this one, following.Elegy
There is nothing built-in, although it's trivial to implement (for some, but not all as JavaScript does not have "named arguments" and specifying an index manual isn't the same, cases presented). Search for "javascript printf" for some leads.Cyb
I don't believe Javascript has anything like this by default. You might be better off trying a Javascript framework or library. If you think it's too much overhead, Google around for "Javascript string formatting" and you might find something you like.Zetland
You might like gist.github.com/1049426 but you can find dozens more just like it. Happy searching.Fianna
O
15

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>
Ogren answered 30/11, 2012 at 5:37 Comment(4)
It enough to use \d instead of \w ?Asare
Unfortunately, no. He has mixed alpha and numeric keys.Ogren
Sorry about the delay. YES. It worked just as you said. Very well done. I do not yet know how to do OO in JavaScript, so this will be a great example for me to suss out.Sansone
Updated with smart JS snippet.Ogren
L
2

This should work similar to python's format but with an object with named keys, it could be numbers as well.

String.prototype.format = function( params ) {
  return this.replace(
    /\{(\w+)\}/g, 
    function( a,b ) { return params[ b ]; }
  );
};

console.log( "hello {a} and {b}.".format( { a: 'foo', b: 'baz' } ) );
//^= "hello foo and baz."
Lawler answered 30/11, 2012 at 5:31 Comment(6)
[^}]+ is better? it won't workwith print( "hello {a-b} and {b}.".format( { 'a-b': 'foo', b: 'baz' } ) );Asare
I confused that you write generic usage of function. But it's not answer. Do not mind.Asare
@mattn: I don't understand, what do you mean by generic?Lawler
I confused that you wrote format function that acceptable all possible words (without {})Asare
underrated answerHujsak
@CesarAugusto exactly right. this is a fantastic answer.Legato

© 2022 - 2024 — McMap. All rights reserved.