Come posso tagliare una stringa in JavaScript?
Tutti i browser da IE9 + hanno trim()
.
Per quei browser che non supportano trim()
, puoi usare questo polyfill da MDN :
if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); }
Guarda questo:
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');}; String.prototype.ltrim=function(){return this.replace(/^\s+/,'');}; String.prototype.rtrim=function(){return this.replace(/\s+$/,'');}; String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
Il taglio da jQuery è conveniente se stai già usando quella struttura.
$.trim(' your string ');
Tendo ad usare spesso jQuery, quindi tagliare le stringhe con esso è naturale per me. Ma è ansible che ci sia una reazione negativa contro jQuery là fuori? 🙂
Sebbene ci siano un sacco di risposte corrette sopra, va notato che l’object String
in JavaScript ha un metodo nativo .trim()
partire da ECMAScript 5 . Quindi idealmente ogni tentativo di prototipare il metodo di assetto dovrebbe davvero verificare se esiste già prima.
if(!String.prototype.trim){ String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,''); }; }
Aggiunto in modo nativo in: JavaScript 1.8.1 / ECMAScript 5
Così supportato in:
Firefox: 3.5+
Safari: 5+
Internet Explorer: IE9 + (solo in modalità Standard!) http://blogs.msdn.com/b/ie/archive/2010/06/25/enhanced-scripting-in-ie9-ecmascript-5-support-and-more aspx
Chrome: 5+
Opera: 10.5+
Tabella di supporto di ECMAScript 5: http://kangax.github.com/es5-compat-table/
Esistono molte implementazioni che possono essere utilizzate. Il più ovvio sembra essere qualcosa del genere:
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); }; " foo bar ".trim(); // "foo bar"
Versione semplice qui Qual è una funzione generale per il trim di JavaScript?
function trim(str) { return str.replace(/^\s+|\s+$/g,""); }
So che questa domanda è stata fatta tre anni prima. Ora, String.trim()
stato aggiunto in modo nativo in JavaScript. Per un’istanza, puoi tagliare direttamente come segue,
document.getElementById("id").value.trim();
Flagrant Badassery ha 11 diversi trim con informazioni di riferimento:
http://blog.stevenlevithan.com/archives/faster-trim-javascript
Le versioni non sorprendentemente basate su espressioni regolari sono più lente del ciclo tradizionale.
Ecco il mio personale. Questo codice è vecchio! L’ho scritto per JavaScript 1.1 e Netscape 3 e da allora è stato aggiornato solo leggermente. (Stringa originale usata).
/** * Trim string. Actually trims all control characters. * Ignores fancy Unicode spaces. Forces to string. */ function trim(str) { str = str.toString(); var begin = 0; var end = str.length - 1; while (begin <= end && str.charCodeAt(begin) < 33) { ++begin; } while (end > begin && str.charCodeAt(end) < 33) { --end; } return str.substr(begin, end - begin + 1); }
Se si utilizza jQuery, utilizzare la funzione jQuery.trim()
. Per esempio:
if( jQuery.trim(StringVariable) == '')
Utilizzare i metodi nativi JavaScript: String.trimLeft()
, String.trimRight()
e String.trim()
.
String.trim()
è supportato in IE9 + e in tutti gli altri browser principali :
' Hello '.trim() //-> 'Hello'
String.trimLeft()
e String.trimRight()
non sono standard, ma sono supportati in tutti i principali browser tranne IE
' Hello '.trimLeft() //-> 'Hello ' ' Hello '.trimRight() //-> ' Hello'
Tuttavia, il supporto di IE è facile con un polyfill:
if (!''.trimLeft) { String.prototype.trimLeft = function() { return this.replace(/^\s+/,''); }; String.prototype.trimRight = function() { return this.replace(/\s+$/,''); }; if (!''.trim) { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } }
Ora puoi usare string.trim () che è un’implementazione nativa di Javascript
var orig = " foo "; console.log(orig.trim());//foo
Guarda anche
String.prototype.trim = String.prototype.trim || function () { return this.replace(/^\s+|\s+$/g, ""); }; String.prototype.trimLeft = String.prototype.trimLeft || function () { return this.replace(/^\s+/, ""); }; String.prototype.trimRight = String.prototype.trimRight || function () { return this.replace(/\s+$/, ""); }; String.prototype.trimFull = String.prototype.trimFull || function () { return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, "").replace(/\s+/g, " "); };
Rubato senza vergogna a Matt duereg .
Tagliare il codice dal progetto angular di js
var trim = (function() { // if a reference is a `String`. function isString(value){ return typeof value == 'string'; } // native trim is way faster: http://jsperf.com/angular-trim-test // but IE doesn't have it... :-( // TODO: we should move this into IE/ES5 polyfill if (!String.prototype.trim) { return function(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; }; } return function(value) { return isString(value) ? value.trim() : value; }; })();
e chiamalo come trim(" hello ")
Ecco un modo molto semplice:
function removeSpaces(string){ return string.split(' ').join(''); }
usa semplicemente il codice
var str = " Hello World! "; alert(str.trim());
Supporto per il browser
Feature Chrome Firefox Internet Explorer Opera Safari Edge Basic support (Yes) 3.5 9 10.5 5 ?
Per il vecchio browser aggiungere il prototipo
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; }
Puoi semplicemente dichiarare la tua variabile come stringa e usare la sua funzione di assetto:
var str = new String('my string'); str= str.trim();
Oggi, praticamente tutti i browser supportano String.prototype.trim()
.
Lo usi in questo modo:
var origStr = ' foo '; var newStr = origStr.trim(); // Value of newStr becomes 'foo'
Nel caso tu abbia ancora bisogno di supportare un browser antico che non supporta questa funzione, questo è un polyfill suggerito dal MDN:
if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; }
Ho una lib che usa trim. così risolto utilizzando il seguente codice.
String.prototype.trim = String.prototype.trim || function(){ return jQuery.trim(this); };
if(!String.prototype.trim){ String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/gm,''); }; }
Dalle risposte precedenti differisce aggiungendo la bandiera m
.
Flag m
cercherà il testo di più linee lineari. In questa modalità, il segno all’inizio e alla fine del pattern ( ^
$
) viene inserito prima e dopo il carattere di nuova riga ( \n
).
Non so quali bug possono hide qui, ma io uso questo:
var some_string_with_extra_spaces=" goes here " console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
O questo, se il testo contiene entra:
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
Un altro tentativo:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
Eccolo in TypeScript:
var trim: (input: string) => string = String.prototype.trim ? ((input: string) : string => { return (input || "").trim(); }) : ((input: string) : string => { return (input || "").replace(/^\s+|\s+$/g,""); })
Tornerà alla regex se il prototipo nativo non è disponibile.
Avevo scritto questa funzione per trim, quando la funzione .trim () non era disponibile in JS nel lontano 2008. Alcuni dei vecchi browser ancora non supportano la funzione .trim () e spero che questa funzione possa aiutare qualcuno.
FUNZIONE TRIM
function trim(str) { var startpatt = /^\s/; var endpatt = /\s$/; while(str.search(startpatt) == 0) str = str.substring(1, str.length); while(str.search(endpatt) == str.length-1) str = str.substring(0, str.length-1); return str; }
Spiegazione : La funzione trim () accetta un object stringa e rimuove eventuali spazi iniziali e finali (spazi, tabulazioni e nuove righe) e restituisce la stringa tagliata. È ansible utilizzare questa funzione per tagliare gli input del modulo per garantire l’invio di dati validi.
La funzione può essere chiamata nel modo seguente come esempio.
form.elements[i].value = trim(form.elements[i].value);
Puoi farlo usando il semplice JavaScript:
function trimString(str, maxLen) { if (str.length <= maxLen) { return str; } var trimmed = str.substr(0, maxLen); return trimmed.substr(0, trimmed.lastIndexOf(' ')) + '…'; } // Let's test it sentenceOne = "too short"; sentencetwo = "more than the max length"; console.log(trimString(sentenceOne, 15)); console.log(trimString(sentencetwo, 15));
Ecco alcuni degli esempi più per tagliare una stringa usando JavaScript .
la mia usa una singola regex per cercare i casi in cui è necessario il ritaglio e usa i risultati di regex per determinare i limiti di sottostringa desiderati:
var illmatch= /^(\s*)(?:.*?)(\s*)$/ function strip(me){ var match= illmatch.exec(me) if(match && (match[1].length || match[2].length)){ me= me.substring(match[1].length, p.length-match[2].length) } return me }
l’unica decisione progettuale che è stata presa in considerazione è stata l’utilizzo di una sottostringa per eseguire l’acquisizione finale. s / \?: // (effettua la cattura a medio termine) e il frammento di sostituzione diventa:
if(match && (match[1].length || match[3].length)){ me= match[2] }
ci sono due scommesse sul rendimento che ho fatto in questi impls:
l’implementazione della sottostringa copia i dati della stringa originale? se è così, nel primo, quando una stringa deve essere ritagliata, c’è un doppio attraversamento, prima nella regex (che può, si spera sia parziale), e la seconda nell’estrazione della sottostringa. si spera che un’implementazione di sottostringa faccia riferimento solo alla stringa originale, quindi operazioni come la sottostringa possono essere quasi libere. incrocia le dita
quanto è buona la cattura nella regex impl? il medio termine, il valore di uscita, potrebbe potenzialmente essere molto lungo. Non ero pronto a mettere in conto che tutte le regex impuls ‘catturate non avrebbero ostacolato un paio di centinaia di KB di input capture, ma non ho nemmeno testato (troppi runtime, scusate!). il secondo SEMPRE esegue una cattura; se il tuo motore è in grado di farlo senza subire un colpo, magari usando alcune delle tecniche di cordatura sopra descritte, Sicuramente USE IT!
Per IE9 + e altri browser
function trim(text) { return (text == null) ? '' : ''.trim.call(text); }