Pergunta

Eu estou tentando mover algum código JavaScript de MicrosoftAjax a JQuery. I usar os equivalentes JavaScript em MicrosoftAjax dos métodos NET populares, por exemplo String.format (), String.StartsWith (), etc. Há equivalentes a eles em jQuery?

Foi útil?

Solução

O código fonte para ASP.NET AJAX é disponíveis para sua referência, para que possa pegar com ele e inclui as partes que você deseja continuar a usar em um arquivo JS separado. Ou, você pode porta-los para jQuery.

Aqui está a função de formatação ...

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

E aqui estão as funções protótipo EndsWith e startsWith ...

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

Outras dicas

Esta é uma simples (e prototípico) variação mais rápida / da função que Josh postou:

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

Uso:

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

Eu uso isso tanto que eu alias-lo apenas para f, mas você também pode usar o mais detalhado format. por exemplo. 'Hello {0}!'.format(name)

Muitas das funções acima (exceto Julian Jelfs de) conter o seguinte erro:

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

Ou, para as variantes que trás contar a partir do final da lista de argumentos:

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

Aqui está uma função correta. É uma variante prototypal de código de Julian Jelfs, o que eu fiz um pouco mais apertado:

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

E aqui está uma versão ligeiramente mais avançada do mesmo, o que lhe permite escapar chaves dobrando-los:

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

Isso funciona corretamente:

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

Aqui é outra boa implementação por Blair Mitchelmore, com um monte de bons recursos extras: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

Feito uma função formato que leva tanto uma coleção ou uma matriz como argumentos

Uso:

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

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

Código:

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

Há uma (um pouco) opção oficial:. jQuery.validator.format

Vem com jQuery Validation Plugin 1.6 (pelo menos).
Bastante semelhante ao String.Format encontrado em .NET.

Editar link fixo quebrado.

Se você estiver usando a validação plugin que você pode usar:

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

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

Apesar de não ser exatamente o que o Q estava pedindo, eu construí um que é semelhante, mas usa o nome espaços reservados em vez de contados. Eu pessoalmente prefiro ter argumentos nomeados e apenas enviar um objeto como um argumento para isso (mais detalhado, mas mais fácil de manter).

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

Aqui está um exemplo de uso ...

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

Nenhuma das respostas apresentadas até agora não tem nenhuma otimização óbvia de usar gabinete para inicializar uma vez e armazenar expressões regulares, para usos posteriores.

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

Além disso, nenhum dos exemplos da aplicação formato aspectos () se já existir.

Usando um navegador moderno, que suporta EcmaScript 2015 (ES6), você pode desfrutar de Modelo de Cordas . Em vez de formatação, você pode diretamente injetar o valor da variável para ele:

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

Observe a seqüência de modelo tem de ser escrito usando back-carrapatos ( `).

Aqui é minha:

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

Não à prova de bala, mas funciona se você usá-lo de forma sensata.

Agora você pode usar Template literais :

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

Way passado o final de temporada, mas Acabei de ser olhando para as respostas dadas e ter o meu valor tuppence:

Uso:

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

Método:

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

Resultado:

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

Aqui está a minha versão que é capaz de escapar '{' e limpar os titulares lugar não atribuídos.

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

A seguinte resposta é provavelmente o mais eficiente, mas tem a ressalva de apenas ser adequado para 1 a 1 mapeamentos de argumentos. Este usa a maneira mais rápida de concatenar strings (semelhantes a um stringbuilder: Disposição de cordas, juntou-se). Este é o meu próprio código. Provavelmente precisa de uma melhor separação embora.

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

Use-o como:

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

Isso viola o princípio DRY, mas é uma solução 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>

Eu não poderia obter a resposta de Josh Stodola ao trabalho, mas a seguir trabalhou para mim. Observe a especificação de prototype. (Testado em 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 realmente deve ser um clone de this de modo a não ser um método destrutivo, mas não é realmente necessário.

Expandindo grande resposta de adamJLev acima , aqui é a versão original datilografado:

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

Eu tenho um Plunker que adiciona-lo para o protótipo string: string.format Não é apenas tão curto quanto alguns dos outros exemplos, mas muito mais flexível.

O uso é semelhante ao c # versão:

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

Além disso, adicionado suporte para o uso de nomes e propriedades do objeto

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

Você também pode conjunto fechamento com substitutos como este.

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

ou você pode tentar bind

'/getElement/_/_/_'.replace(/_/g, (function(_) {return this.ar[this.i++];}).bind({ar: ["invoice", "id", 1337],i: 0}))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top