Manipolazione tokens e paths tramite String

Di seguito sono presenti alcune funzioni di utilità generale che consentono di manipolare stringhe contenenti paths e tokens formattati tramite grammatica CSV

First Token

Ritorna il primo token della stringa dato uno splitter


if (!String.prototype.firstToken) {
  String.prototype.firstToken = function (splitter) {
    var tokens = this.split(splitter);
    if (tokens && tokens.length > 0)
      return tokens[0];
    else
      return this;
  };
}

Last Token

Ritorna l’ultimo token della stringa dato uno splitter

if (!String.prototype.lastToken) {
String.prototype.lastToken = function (splitter) {
var tokens = this.split(splitter);
if (tokens && tokens.length > 0)
return tokens[tokens.length - 1];
else
return this;
};

All Except Last Token And Splitter

Ritorna tutto il path eccetto l’ultimo token ed il precedente splitter, in poche parole tronca il path a livello dell’lultimo token

if (!String.prototype.allExceptLastTokenAndSplitter) {
String.prototype.allExceptLastTokenAndSplitter = function (splitter) {
var i = this.lastIndexOf(splitter);
if (i >= 0)
return this.substring(0, i);
else
return this;
};

All Except Last Token

Ritorna tutto il path eccetto l’ultimo token, in poche parole tronca il path a livello dell’ultimo token omettendo anche l’ultimo splitter

if (!String.prototype.allExceptLastToken) {
String.prototype.allExceptLastToken = function (splitter) {
var i = this.lastIndexOf(splitter);
if (i >= 0)
return this.substring(0, i) + splitter;
else
return this;
};
}

Replace Last Token

Rimpiazza l’ultimo token del path con il token dato

if (!String.prototype.replaceLastToken) {
String.prototype.replaceLastToken = function (splitter, newToken) {
var i = this.lastIndexOf(splitter);
if (i >= 0)
return this.substring(0, i) + splitter + newToken;
else
return this;
};
}

Equivalente di “String.Format” (.NET) per Javascript

La funzione “System.String.Format” presente in dotNET è tra le più utili e fondamentali dell’ambiente. Sfortunatamente in Javascript non esiste nulla di simile. Il codice seguente consente di compensare questa lacuna.

Codice

if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}