JavaScript non dispone di un metodo nativo per rimuovere il primo e l'ultimo carattere da una stringa. Tuttavia, grazie alla prototipizzazione, รจ facile creare questo metodo per le stringhe. Vediamo come fare.
Il seguente codice fa uso del metodo substring()
:
if(typeof String.prototype.chop !== 'function') {
String.prototype.chop = function() {
var str = this.substring(1, this.length - 1);
return str;
}
}
Esempio pratico:
var btn = document.querySelector('#run'),
test = document.querySelector('#test');
btn.addEventListener('click', function() {
var text = test.firstChild.nodeValue;
test.innerHTML = text.chop();
}, false);
Potete visionare l'esempio finale in questa pagina.