Odpowiednik String.format w jQuery

Próbuję przenieść kod JavaScript z MicrosoftAjax do JQuery. Używam odpowiedników JavaScript w MicrosoftAjax popularnych metod. NET, np. String.format (), String.startsWith (), itd. Czy w jQuery są ich odpowiedniki?

Author: abatishchev, 2009-06-24

20 answers

Kod źródłowy dla ASP.NET AJAX jest dostępny w celach informacyjnych, więc możesz go przeglądać i dołączać części, których chcesz nadal używać do osobnego pliku JS. Możesz też przenieść je do jQuery.

Oto funkcja formatowania...

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

A oto koniec i początek funkcji prototypowych...

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);
}
 187
Author: Josh Stodola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-06-24 15:10:35

Jest to szybsza/prostsza (i prototypowa) odmiana funkcji, którą napisał 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;
};

Użycie:

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

Używam tego tak dużo, że aliased go po prostu f, ale można również użyć bardziej zwrotny format. np. 'Hello {0}!'.format(name)

 144
Author: adamJLev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-23 19:30:30

Wiele z powyższych funkcji (oprócz Juliana Jelfsa) zawiera następujący błąd:

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

Lub dla wariantów, które liczą się wstecz od końca listy argumentów:

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

Oto prawidłowa funkcja. Jest to prototypowy wariant kodu Juliana Jelfsa, który zrobiłem nieco ciaśniej: {]}

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

A oto nieco bardziej zaawansowana wersja tego samego, która pozwala na ucieczkę z aparatów ortodontycznych poprzez ich podwojenie:

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

To działa poprawnie:

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

Tutaj to kolejna dobra implementacja Blair Mitchelmore, z mnóstwem fajnych dodatkowych funkcji: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

 125
Author: gpvos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-02 14:26:32

Stworzył funkcję formatującą, która przyjmuje jako argumenty kolekcję lub tablicę

Użycie:

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

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

Kod:

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];
    });
};
 46
Author: ianj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-01 22:23:44

Istnieje (nieco) oficjalna opcja: jQuery.walidator.format .

Pochodzi z jQuery Validation Plugin 1.6 (co najmniej).
Bardzo podobne do String.Format Znalezione w .NET.

Edycja Naprawiono uszkodzony link.

 36
Author: rsenna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-02 12:51:55

Jeśli używasz wtyczki validation możesz użyć:

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

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

 15
Author: fiestacasey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-02 11:32:38

Chociaż nie dokładnie to, o co prosiło Q, zbudowałem podobny, ale używa nazwanych zastępczych zamiast numerowanych. Osobiście wolę mieć nazwane argumenty i po prostu wysłać obiekt jako argument do niego (bardziej gadatliwy, ale łatwiejszy do utrzymania).

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

Oto przykładowe użycie...

alert("Hello {name}".format({ name: 'World' }));
 12
Author: Brian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-21 03:29:11

Żadna z przedstawionych dotąd odpowiedzi nie ma oczywistej optymalizacji użycia enclosure do jednorazowej inicjalizacji i przechowywania wyrażeń regularnych, dla kolejnych zastosowań.

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

Ponadto żaden z przykładów nie respektuje implementacji format (), jeśli już istnieje.

 6
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-07 01:03:24

Oto moje:

String.format = function(tokenised){
        var args = arguments;
        return tokenised.replace(/{[0-9]}/g, function(matched){
            matched = matched.replace(/[{}]/g, "");
            return args[parseInt(matched)+1];             
        });
    }
Nie jest kuloodporny, ale działa, jeśli używasz go rozsądnie.
 4
Author: Julian Jelfs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-04 09:55:12

Korzystając z nowoczesnej przeglądarki, która obsługuje EcmaScript 2015 (ES6), możesz cieszyć się ciągi szablonów. Zamiast formatowania, możesz bezpośrednio wprowadzić do niej wartość zmiennej:

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

Uwaga łańcuch szablonu musi być zapisany za pomocą back-ticks (`).

 4
Author: david,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-09 04:12:17

Oto moja wersja, która jest w stanie uciec ' { ' , i oczyścić te nieprzypisane uchwyty miejsca.

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);
}
 2
Author: Feng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-23 19:22:37

Następująca odpowiedź jest prawdopodobnie najbardziej efektywna, ale ma zastrzeżenie, że nadaje się tylko do odwzorowania 1 do 1 argumentów. Używa najszybszego sposobu łączenia łańcuchów (podobnie jak stringbuilder: array of strings, joined). To mój własny kod. Pewnie jednak potrzebuje lepszego separatora.

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

Użyj go jak:

alert(String.format("<a href='~'>~</a>", ["one", "two"]));
 2
Author: Skychan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-03 19:05:33

Teraz możesz użyć literały szablonów :

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);
 2
Author: Arek Kostrzeba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-24 23:38:33

To narusza zasadę suchości, ale jest to zwięzłe rozwiązanie:

var button = '<a href="{link}" class="btn">{text}</a>';
button = button.replace('{text}','Authorize on GitHub').replace('{link}', authorizeUrl);
 1
Author: ilyaigpetrov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-19 01:58:17

[[3]] dawno temu, ale właśnie patrzyłem na udzielone odpowiedzi i mam swoje tuppence warte:

Użycie:

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

Metoda:

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

Wynik:

"aalert" is not defined
3.14 3.14 a{2}bc foo
 1
Author: RickL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 01:28:30
<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>
 0
Author: Kishor Dalwadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-27 02:31:34

Nie mogłem uzyskać odpowiedzi Josha Stodoli do pracy, ale poniższe zadziałały dla mnie. Zwróć uwagę na specyfikację prototype. (Testowane na IE, FF, Chrome i 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 naprawdę powinien być klonem z this, aby nie być destrukcyjną metodą, ale nie jest to naprawdę konieczne.

 0
Author: JellicleCat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-03 19:26:52

Rozszerzając świetną odpowiedź adamjleva powyżej , oto wersja maszynopisu:

// 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;
};
 0
Author: Annie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:24

Mam plunker, który dodaje go do prototypu ciągów: string.format Nie jest tak krótki jak niektóre z innych przykładów, ale o wiele bardziej elastyczny.

Użycie jest podobne do wersji 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

Dodano również wsparcie dla używania nazw i właściwości obiektów

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
 0
Author: ShrapNull,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-14 15:30:44

Możesz również zamknąć tablicę za pomocą takich zamienników.

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

Lub możesz spróbować bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
 0
Author: test30,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-10 02:55:18