Domanda

Così ho un cliente che non permette alcuna codifica lato server, se non in rare occorrenze ASP classico, quindi tutto è HTML e JavaScript.

Quindi, in pratica ho bisogno di costruire un URL dalla forma e quindi reindirizzare. Javascript non è necessariamente il mio genere, ma questo mi avrebbe portato a 5 minuti in asp.net utilizzando String.Format.

Esiste un metodo String.Format in JavaScript?

È stato utile?

Soluzione

Ahi, che fa schifo.

:

String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

Altri suggerimenti

No, non c'è nulla di simile in javascript, ma alcune persone hanno già scritto un printf per js

JavaScript equivalente a printf / String.Format

Ero alla ricerca di una cosa simile e optato per oggetto "Modello" di Prototype.

Dalla esempi il prototipo

// the template (our formatting expression) var myTemplate = new Template( 'The TV show #{title} was created by #{author}.');

// our data to be formatted by the template var show = { title: 'The Simpsons', author: 'Matt Groening', network: 'FOX' };

// let's format our data myTemplate.evaluate(show); // -> "The TV show The Simpsons was created by Matt Groening."

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top