abalter abalter - 1 month ago 7
Javascript Question

Javascript equivalent to python's .format()

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

Answer

Ok, here's what I got for you so far..... based on JavaScript equivalent to printf/string.format

I got the last 3 examples working. Only the first one with no keys isn't working yet.

EDIT: Ok, all done... works for all your cases now. 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>