Javascript PHP sprintf equivalent

Asked

Viewed 173 times

5

Instead of doing:

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

I’m making:

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 several occurrences.

Is there any "official" way or each has to solve on their own by creating a custom function?

I found a couple of old plugins for jQuery, 2007 and 2008. Did anything change from there to here? The frameworks Javascript, like jQuery or Mootools, already incorporate this? If so, what is the JS behind it?

  • There is the conveniently baptized sprintf.js, although it is not native

  • I usually use the Mootools element builder for cases similar to what you put http://jsfiddle.net/j1tknqj7/, but I think a JS version of sprintf does not exist. I will put a suggestion when my child is in bed and if there is not yet a good suggestion.

  • There are template systems that solve this. With handlebars or mustache, you would have '<a href="{{href}}" title="{{title}}">{{desc}}</a>' compiled as template, and then only passes the object data for the template he solves.

  • @bfavaretto, I forgot to comment that my inspiration came from moustache. My intention is something more basic for handling html strings within js code.

4 answers

2

In Ecmascript 6 (ES6), the latest version of the Javascript specification, there are strings template, that allow for something similar:

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.

2

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);

Thus, you can build jQuery elements, which contains an Htmlelement. With this you can manipulate the element like recording events, inserting other elements, etc, even before the object is in the document.

As asked, the first element you pass 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!), such as {href: 'valor', class: 'umaClasse', type: 'button'}.

Creating elements with jQuery - jQuery API

  • What other parameters can I use in the constructor? It would be nice to link to documentation...

1

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 exit would be:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.