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

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito utilizza Akismet per ridurre lo spam. Scopri come vengono elaborati i dati derivati dai commenti.