Frage

Ich versuche, einige JavaScript-Code von MicrosoftAjax zu JQuery zu bewegen. Ich verwende den JavaScript-Äquivalente in MicrosoftAjax der populären .net Methoden, z.B. String.format (), String.StartsWith () usw. Gibt es ihnen in jQuery-Äquivalente?

War es hilfreich?

Lösung

Die Quellcode für ASP.NET AJAX ist verfügbar für Ihre Referenz, so dass Sie durch sie wählen können und sind die Teile, die Sie mit in eine separate JS-Datei fortgesetzt werden soll. Oder Sie können Portierung auf jQuery.

Hier ist das Format, Funktion ...

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

Und hier sind die endsWith und starts Prototyp Funktionen ...

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

Andere Tipps

Dies ist eine schnelle / einfacher (und prototypische) Variation der Funktion, die Josh geschrieben:

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

Verbrauch:

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

Ich benutze dies so sehr, dass ich es aliased nur f, aber Sie können auch die ausführlichere format verwenden. z.B. 'Hello {0}!'.format(name)

Viele der oben genannten Funktionen (mit Ausnahme von Julian Jelfs ist) enthalten die folgende Fehlermeldung:

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

Oder für die Varianten, die rückwärts vom Ende der Argumentliste zählen:

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

Hier ist eine korrekte Funktion. Es ist eine prototypische Variante von Julian Jelfs des Codes, die ich etwas enger gemacht:

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

Und hier ist eine etwas erweiterte Version des gleichen, die Sie Klammern zu entkommen, indem sie eine Verdoppelung ihnen erlaubt:

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

Das funktioniert richtig:

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

Hier ist eine weitere gute Umsetzung von Blair Mitchelmore, mit einem Bündel von schönen Extra-Features: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

eine Funktion Format hergestellt, die entweder eine Sammlung oder ein Array als Argument

nimmt

Verbrauch:

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

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

Code:

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

Es gibt eine (etwas) offizielle Option. jQuery.validator.format

Kommt mit jQuery Validierung Plugin 1.6 (zumindest).
Ganz ähnlich wie die String.Format in .NET gefunden.

Bearbeiten Fixed Defekten Link.

Wenn Sie die Validierung Plugin verwenden können Sie:

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

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

Obwohl es nicht genau das, was die Q bittet um, ich habe eine gebaut, die ähnlich ist, aber verwendet Platzhalter anstelle von nummerierten benannt. Ich persönlich ziehe benannten Argumente hat und nur in einem Objekt als Argument, um es (ausführlicher, aber leichter zu pflegen) zu senden.

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

Hier ist ein Beispiel für die Verwendung ...

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

Keine der bisher vorgestellten Antworten hat keine offensichtliche Optimierungs Gehäuse der Verwendung einmal zu initialisieren und reguläre Ausdrücke zu speichern, für die nachfolgenden Verwendungen.

// 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($0) {
            var idx = 1 * $0.match(rx2)[0];
            return args[idx] !== undefined ? args[idx] : (args[idx] === "" ? "" : $0);
        });
    }
}());

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

Auch keines der Beispiele respektiert Format () -Implementierung, wenn man bereits vorhanden ist.

einen modernen Browser verwenden, der EcmaScript 2015 (ES6) unterstützt, können Sie genießen Template Strings . Statt Formatierung können Sie direkt den Variablenwert in sie injizieren:

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

die Vorlage Zeichenfolge Hinweis hat geschrieben werden unter Verwendung von Back-Zecken ( `).

Hier ist meins:

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

Nicht kugelsicher, aber funktioniert, wenn Sie es sinnvoll nutzen.

Jetzt können Sie verwenden Vorlage Literale :

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

Weg vorbei am Ende der Saison, aber ich habe bei den Antworten gerade gegeben suchen und habe meine tuppence Wert:

Verbrauch:

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

Methode:

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

Ergebnis:

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

Hier ist meine Version der in der Lage ist, zu entkommen ‚{‘, und reinigen Sie diese nicht zugeordneten Platzhalter auf.

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

Die folgende Antwort ist wahrscheinlich die effizienteste, hat aber den Nachteil von nur geeignet ist, für 1 bis 1 Zuordnungen von Argumenten. Dies verwendet den schnellsten Weg, Strings verketten (ähnlich einen Stringbuilder: Array von Strings, verbunden). Das ist mein eigener Code. Wahrscheinlich braucht einen besseren Separator though.

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("");
}

Verwenden Sie es mögen:

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

Das verletzt DRY-Prinzip, aber es ist eine kurze Lösung:

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>

Ich konnte nicht Josh Stodola Antwort an der Arbeit, aber die für mich folgende gearbeitet. Beachten Sie die Spezifikation von prototype. (Getestet auf IE, FF, Chrome und 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 sollte wirklich ein Klon sein von this, um nicht eine destruktive Methode zu sein, aber es ist nicht wirklich notwendig.

Der Ausbau auf adamJLev die große Antwort oben , hier ist die Typoskript Version:

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

Ich habe eine Plunker, dass es auf den String Prototyp fügt hinzu: string.format Es ist nicht nur so kurz wie einige der anderen Beispiele, aber viel flexibler.

Die Verwendung ist ähnlich wie c # Version:

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

Auch zusätzliche Unterstützung für Namen und Objekteigenschaften

mit
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

Sie können auch Verschluss Array mit Ersatz wie diese.

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

oder Sie können versuchen bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top