Domanda

Sto cercando di spostare del codice JavaScript da MicrosoftAjax a JQuery. Uso gli equivalenti JavaScript in MicrosoftAjax dei popolari metodi .net, ad es. String.format (), String.startsWith (), ecc. Esistono equivalenti a loro in jQuery?

È stato utile?

Soluzione

Il il codice sorgente di ASP.NET AJAX è disponibile come riferimento, quindi è possibile selezionarlo e includere le parti che si desidera continuare a utilizzare in un file JS separato. Oppure, puoi portarli su jQuery.

Ecco la funzione di formattazione ...

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

Ed ecco le estremità Con e inizia Con funzioni prototipo ...

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

Altri suggerimenti

Questa è una variazione più rapida / semplice (e prototipica) della funzione pubblicata da Josh:

String.prototype.format = String.prototype.f = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

Utilizzo:

'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7) 

Lo uso così tanto che l'ho impostato solo su f , ma puoi anche usare il più dettagliato formato . per esempio. 'Hello {0}!'. format (name)

Molte delle funzioni di cui sopra (eccetto quelle di Julian Jelfs) contengono il seguente errore:

js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo

Oppure, per le varianti che contano all'indietro dalla fine dell'elenco degli argomenti:

js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo

Ecco una funzione corretta. È una variante prototipo del codice di Julian Jelfs, che ho reso un po 'più stretto:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

Ed ecco una versione leggermente più avanzata della stessa, che ti permette di sfuggire alle parentesi raddoppiandole:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
    if (m == "{{") { return "{"; }
    if (m == "}}") { return "}"; }
    return args[n];
  });
};

Funziona correttamente:

js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo

Ecco un'altra buona implementazione di Blair Mitchelmore, con un sacco di belle funzioni extra: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

Creata una funzione di formato che accetta una raccolta o un array come argomenti

Utilizzo:

format("i can speak {language} since i was {age}",{language:'javascript',age:10});

format("i can speak {0} since i was {1}",'javascript',10});

Codice:

var format = function (str, col) {
    col = typeof col === 'object' ? col : Array.prototype.slice.call(arguments, 1);

    return str.replace(/\{\{|\}\}|\{(\w+)\}/g, function (m, n) {
        if (m == "{{") { return "{"; }
        if (m == "}}") { return "}"; }
        return col[n];
    });
};

Esiste un'opzione (in qualche modo) ufficiale: jQuery.validator.format .

Viene fornito con jQuery Validation Plugin 1.6 (almeno).
Abbastanza simile al String.Format trovato in .NET.

Modifica Corretto collegamento interrotto.

Se stai usando il plugin di validazione puoi usare:

jQuery.validator.format (" {0} {1} " ;, " cool " ;, " formattazione ") = 'cool formattazione'

http://docs.jquery.com/Plugins/Validation/jQuery.validator.format #templateargumentargumentN ...

Sebbene non sia esattamente quello che chiedeva la Q, ne ho costruito uno simile ma che utilizza segnaposto nominati anziché numerati. Personalmente preferisco aver chiamato argomenti e inviare semplicemente un oggetto come argomento (più dettagliato, ma più facile da mantenere).

String.prototype.format = function (args) {
    var newStr = this;
    for (var key in args) {
        newStr = newStr.replace('{' + key + '}', args[key]);
    }
    return newStr;
}

Ecco un esempio di utilizzo ...

alert("Hello {name}".format({ name: 'World' }));

Nessuna delle risposte presentate finora non ha un'ovvia ottimizzazione dell'uso del contenitore per inizializzare una volta e memorizzare espressioni regolari, per usi successivi.

// DBJ.ORG string.format function
// usage:   "{0} means 'zero'".format("nula") 
// returns: "nula means 'zero'"
// place holders must be in a range 0-99.
// if no argument given for the placeholder, 
// no replacement will be done, so
// "oops {99}".format("!")
// returns the input
// same placeholders will be all replaced 
// with the same argument :
// "oops {0}{0}".format("!","?")
// returns "oops !!"
//
if ("function" != typeof "".format) 
// add format() if one does not exist already
  String.prototype.format = (function() {
    var rx1 = /\{(\d|\d\d)\}/g, rx2 = /\d+/ ;
    return function() {
        var args = arguments;
        return this.replace(rx1, function(<*>) {
            var idx = 1 * <*>.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : <*>);
        });
    }
}());

alert("{0},{0},{{0}}!".format("{X}"));

Inoltre, nessuno degli esempi rispetta l'implementazione del formato () se ne esiste già uno.

Utilizzando un browser moderno, che supporta EcmaScript 2015 (ES6), puoi goderti Stringhe modello . Invece di formattare, puoi inserire direttamente il valore della variabile in esso:

var name = "Waleed";
var message = `Hello ${name}!`;

Nota che la stringa del modello deve essere scritta usando back-ticks (`).

Ecco il mio:

String.format = function(tokenised){
        var args = arguments;
        return tokenised.replace(/{[0-9]}/g, function(matched){
            matched = matched.replace(/[{}]/g, "");
            return args[parseInt(matched)+1];             
        });
    }

Non a prova di proiettile ma funziona se lo usi in modo ragionevole.

Ora puoi usare Letterature di modelli :

var w = "the Word";
var num1 = 2;
var num2 = 3;

var long_multiline_string = `This is very long
multiline templete string. Putting somthing here:
${w}
I can even use expresion interpolation:
Two add three = ${num1 + num2}
or use Tagged template literals
You need to enclose string with the back-tick (\` \`)`;

console.log(long_multiline_string);

Molto oltre la fine della stagione, ma ho appena esaminato le risposte fornite e valgo la mia tuppence:

Utilizzo:

var one = strFormat('"{0}" is not {1}', 'aalert', 'defined');
var two = strFormat('{0} {0} {1} {2}', 3.14, 'a{2}bc', 'foo');

Metodo:

function strFormat() {
    var args = Array.prototype.slice.call(arguments, 1);
    return arguments[0].replace(/\{(\d+)\}/g, function (match, index) {
        return args[index];
    });
}

Risultato:

"aalert" is not defined
3.14 3.14 a{2}bc foo

Ecco la mia versione in grado di sfuggire a "{" e ripulire quei segnaposti non assegnati.

function getStringFormatPlaceHolderRegEx(placeHolderIndex) {
    return new RegExp('({)?\\{' + placeHolderIndex + '\\}(?!})', 'gm')
}

function cleanStringFormatResult(txt) {
    if (txt == null) return "";

    return txt.replace(getStringFormatPlaceHolderRegEx("\\d+"), "");
}

String.prototype.format = function () {
    var txt = this.toString();
    for (var i = 0; i < arguments.length; i++) {
        var exp = getStringFormatPlaceHolderRegEx(i);
        txt = txt.replace(exp, (arguments[i] == null ? "" : arguments[i]));
    }
    return cleanStringFormatResult(txt);
}
String.format = function () {
    var s = arguments[0];
    if (s == null) return "";

    for (var i = 0; i < arguments.length - 1; i++) {
        var reg = getStringFormatPlaceHolderRegEx(i);
        s = s.replace(reg, (arguments[i + 1] == null ? "" : arguments[i + 1]));
    }
    return cleanStringFormatResult(s);
}

La seguente risposta è probabilmente la più efficiente, ma ha la premessa di essere adatta solo per 1 a 1 mapping di argomenti. Questo utilizza il modo più veloce di concatenare le stringhe (simile a un costruttore di stringhe: array di stringhe, unito). Questo è il mio codice Probabilmente ha bisogno di un separatore migliore però.

String.format = function(str, args)
{
    var t = str.split('~');
    var sb = [t[0]];
    for(var i = 0; i < args.length; i++){
        sb.push(args[i]);
        sb.push(t[i+1]);
    }
    return sb.join("");
}

Usalo come:

alert(String.format("<a href='~'>~</a>", ["one", "two"]));

Ciò viola il principio DRY, ma è una soluzione concisa:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
<html>
<body>
<script type="text/javascript">
   var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
   document.write(FormatString(str));
   function FormatString(str) {
      var args = str.split(',');
      for (var i = 0; i < args.length; i++) {
         var reg = new RegExp("\\{" + i + "\\}", "");             
         args[0]=args[0].replace(reg, args [i+1]);
      }
      return args[0];
   }
</script>
</body>
</html>

Non sono riuscito a ottenere la risposta di Josh Stodola al lavoro, ma quanto segue ha funzionato per me. Nota le specifiche di prototype . (Testato su IE, FF, Chrome e Safari.):

String.prototype.format = function() {
    var s = this;
    if(t.length - 1 != args.length){
        alert("String.format(): Incorrect number of arguments");
    }
    for (var i = 0; i < arguments.length; i++) {       
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }
    return s;
}

s dovrebbe davvero essere un clone di this in modo da non essere un metodo distruttivo, ma non è davvero necessario.

Espandendo la grande risposta di adamJLev sopra , ecco la versione di TypeScript:

// Extending String prototype
interface String {
    format(...params: any[]): string;
}

// Variable number of params, mimicking C# params keyword
// params type is set to any so consumer can pass number
// or string, might be a better way to constraint types to
// string and number only using generic?
String.prototype.format = function (...params: any[]) {
    var s = this,
        i = params.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), params[i]);
    }

    return s;
};

Ho un plunker che lo aggiunge al prototipo di stringa: string.format Non è solo breve come alcuni degli altri esempi, ma molto più flessibile.

L'utilizzo è simile alla versione c #:

var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy"); 
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array

Inoltre, è stato aggiunto il supporto per l'utilizzo di nomi e amp; proprietà dell'oggetto

var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"}); 
//result: Meet you on Thursday, ask for Frank

Puoi anche chiudere l'array con sostituzioni come questa.

var url = '/getElement/_/_/_'.replace(/_/g, (_ => this.ar[this.i++]).bind({ar: ["invoice", "id", 1337],i: 0}))
> '/getElement/invoice/id/1337

oppure puoi provare bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top