Equivalent to PHP sprintf in JavaScript

4

Instead of doing:

var html = '<a href="' + data.href + '" title="' + data.title + '">' + data.desc + '</a>';

I'm doing:

var html = '<a href="{href}" title="{title}">{desc}</a>';

html = html
     .replace( '{href}',  data.href )
     .replace( '{title}', data.title )
     .replace( '{desc}',  data.desc );

Or replace( /{nome}/g, data.nome ) if there are multiple occurrences.

Is there any "official" way or does each have to resolve on your own by creating a custom function?

I found a couple of legacy plugins for jQuery, 2007 and 2008 . Has anything changed from there to here? Do JavaScript frameworks, such as jQuery or Mootools, already incorporate this? If so, what is the JS behind it?

    
asked by anonymous 15.10.2014 / 18:50

4 answers

2

With jQuery you can use your element builder:

var $elemento = $("<a>", {href: data.href, title: data.title}).text(data.desc);
$('.umContainerParaNossoElemento').html($elemento);
console.log("Versão string: " + $elemento[0].outterHTML);

So you can build jQuery elements, which contain an HTMLElement. With this you can manipulate the element as register events, insert other elements, etc., even before the object is in the document.

As asked, the first element you pass is the string of the tag (s) you want to create as < div> or < ul>< li> . The second argument is an object with the values of the tag attributes, in camel case (HTML is case insensitive!), As {href: 'valor', class: 'umaClasse', type: 'button'} .

Creating elements with jQuery - jQuery API

    
15.10.2014 / 20:35
2

For your good fortune there are a few people interested in turning PHP's functions into JS and you'll find a lot on link .

The equivalent of sprintf is this link

>

Good luck!

    
15.10.2014 / 20:04
2

In ECMAScript 6 (ES6), the latest version of the JavaScript specification, there are template strings , which allow something like this:

var a = 5;
var b = 10;
console.log('Fifteen is ${a + b} and\nnot ${2 * a + b}.');

And the good news: this already works in Chrome, Firefox, Opera, and Edge.

    
20.10.2015 / 18:57
0

My solution to this would be to add a method to prototype of String :

 String.prototype.format = function()
 {
    var args = arguments;

    return this.replace(/\{(\d+)\}/g, function(text, key)
    {
        return args[key];
    });
 }

Then we could make the following call:

"Meu nome é '{0}' e estou no site <strong>{1}</strong>".format('Wallace', 'StackOverlow')

The output would be:

"Meu nome é 'Wallace' e estou no site <strong>StackOverlow</strong>

I got the idea to write this language function called Python .

    
10.03.2016 / 16:11