2011-11-15 7 views
24

In javascript, come posso fare un assetto giusto?javascript devi fare un assetto giusto

Ho il seguente:

var s1 = "this is a test~"; 

    var s = s1.rtrim('~') 

ma non ha avuto successo

+0

Top hit su google: http://blog.stevenlevithan.com/archives/faster-trim-javascript – Tessmore

risposta

57

Utilizzare un RegExp. Non dimenticare di sfuggire a personaggi speciali.

s1 = s1.replace(/~+$/, ''); //$ marks the end of a string 
          // ~+$ means: all ~ characters at the end of a string 
+0

Perfetto, grazie! –

2

Una soluzione con un espressione regolare:

"hi there~".replace(/~*$/, "") 
2

Non ci sono alcun assetto, ltrim, o funzioni rtrim in Javascript. Molte biblioteche forniscono loro, ma in generale si cercherà qualcosa di simile:

str.replace(/~*$/, ''); 

Per finiture giuste, il seguente è generalmente più veloce di un regex a causa di come regex si occupa di caratteri finali nella maggior parte dei browser:

function rtrim(str, ch) 
{ 
    for (i = str.length - 1; i >= 0; i--) 
    { 
     if (ch != str.charAt(i)) 
     { 
      str = str.substring(0, i + 1); 
      break; 
     } 
    } 
    return str; 
} 
5

È possibile modificare il prototipo String se lo si desidera. La modifica del prototipo String è generalmente disapprovata, ma personalmente preferisco questo metodo, in quanto rende IMHO il pulitore del codice.

String.prototype.rtrim = function(s) { 
    return this.replace(new RegExp(s + "*$"),''); 
}; 

Quindi chiamare ...

var s1 = "this is a test~"; 
var s = s1.rtrim('~'); 
alert(s); 
-1

Questo è vecchio, lo so. Ma non vedo cosa c'è di sbagliato nel substr ...?

function rtrim(str, length) { 
    return str.substr(0, str.length - length); 
} 
+0

L'unico problema qui è che potrebbe esserci un numero qualsiasi di caratteri alla fine della stringa ... diciamo invece di "questo è test ~" hanno avuto "questo è test ~~~" o anche nessuno "questo è test'. Il tuo caso funziona comunque bene per tagliare un determinato numero di caratteri dalla stringa, indipendentemente da quale sia il carattere – bobkingof12vs

1

IMO questo è il modo migliore per fare un giusto assetto/sinistra e, quindi, avere una funzionalità completa per il taglio (dal javascript supporta string.trim nativamente) esempio

String.prototype.rtrim = function (s) { 
    if (s == undefined) 
     s = '\\s'; 
    return this.replace(new RegExp("[" + s + "]*$"), ''); 
}; 
String.prototype.ltrim = function (s) { 
    if (s == undefined) 
     s = '\\s'; 
    return this.replace(new RegExp("^[" + s + "]*"), ''); 
}; 

Usage:

var str1 = ' jav ' 
var r1 = mystring.trim();  // result = 'jav' 
var r2 = mystring.rtrim();  // result = ' jav' 
var r3 = mystring.rtrim(' v'); // result = ' ja' 
var r4 = mystring.ltrim();  // result = 'jav ' 
Problemi correlati