Come faccio a tagliare una stringa in JavaScript?
L'assetto di jQuery è conveniente se state già usando quel framework.
$.trim(' your string ');
Io tendo ad usare spesso jQuery, quindi tagliare le stringhe con esso è naturale per me. Ma è possibile che ci sia un contraccolpo contro jQuery là fuori? :)
Ci sono molte implementazioni che possono essere utilizzate. La più ovvia sembra essere qualcosa come questa:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
};
" foo bar ".trim(); // "foo bar"
Versione semplice qui Cos'è una funzione generale per l'assetto JavaScript?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}