0

Well , in python or java or ... we do sth like : (the python version )

tmp = "how%s" %("isit") 

and now tmp looks like "howisit".
is there any bulit in thing like that in javascript ? ( rather than sprintf )

Thanks

1

5 Answers 5

2

Not build in, but you can make your own templating by extending the String prototype:

String.prototype.template = String.prototype.template ||
   function(){
    var args = arguments;
    function replacer(a){
        return args[Number(a.slice(1))-1] || a;
    }
    return this.replace(/(\$)?\d+/gm,replacer)
   };
// usages
'How$1'.template('isit'); //=> Howisit
var greet = new Date('2012/08/08 08:00') < new Date 
             ? ['where','yesterday'] : ['are','today'];
'How $1 you $2?'.template(greet[0],greet[1]); // How where you yesterday?
Sign up to request clarification or add additional context in comments.

Comments

1

Nop, there isn't. You can do string concatenation.

var tmp = 'how' + 'isit';

Or replace in other situations. This is a stupid example but you get the idea:

var tmp = 'how{0}'.replace('{0}', 'isit');

Comments

0

No, there is no string formating built in to javascript.

Comments

0

No builtin function is there, however you can very easily build one yourself. The replace function can take a function argument and is the perfect solution for this work. Although be careful with large strings and complicated expressions as this might get slow quickly.

var formatString = function(str) {
    // get all the arguments after the first
    var replaceWith = Array.prototype.slice.call(arguments, 1);
    // simple replacer based on String, Number
    str.replace(/%\w/g, function() {
        return replaceWith.shift();
    });
};

var newString = formatString("how %s %s?", "is", "it");

Comments

0

I think you can use these (simplistic) snippets;

function formatString(s, v) {
  var s = (''+ s), ms = s.match(/(%s)/g), m, i = 0;
  if (!ms) return s;
  while(m = ms.shift()) {
     s = s.replace(/(%s)/, v[i]);
     i++;
  }
  return s;
}

var s = formatString("How%s", ["isit"]);

Or;

String.prototype.format = function() {
    var s = (""+ this), ms = s.match(/(%s)/g) || [], m, v = arguments, i = 0;
    while(m = ms.shift()) {
        s = s.replace(/(%s)/, v[i++]);
    }
    return s;
}

var s = "id:%s, name:%s".format(1,"Kerem");
console.log(s);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.