Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
52 lines (51 sloc) 2.14 KB
<?xml version="1.0" encoding="UTF-8"?>
<CONTENT TITLE="Strings and RegExp" ID="strings">
<CONTENT TITLE="How do I trim whitespace?" ID="trimString" NUMID="4_16">
<P>
ECMAScript Edition 5 specifies <ICODE>String.prototype.trim()</ICODE>. Where not implemented,
it can be defined as a method that uses a <DFN>regular expression</DFN>:
</P>
<CODE>
if (typeof String.prototype.trim != "function")
{
String.prototype.trim = function () {
return this.replace(/^\s+/, "").replace(/\s+$/, "");
};
}
</CODE>
<P>
Implementations are inconsistent with <ICODE>\s</ICODE>. For example,
some implementations, notably JScript 5.8 and Safari 2, do not match <ICODE>\xA0</ICODE>
(no-break space), among others.</P>
<P>
A more consistent approach would be to create a character class
that defines the characters to trim. For example, the following
method trims exactly the characters that should be trimmed by
a conforming implemenation of ECMAScript Ed. 5.1 (<i>WhiteSpace</i>
and <i>LineTerminator</i>):
</P>
<CODE>
if (typeof String.prototype.trim != "function")
{
String.prototype.trim = (function () {
var sWhiteSpace = "[\\u0009\\u000A-\\u000D\\u0020\\u00A0"
+ "\\uFEFF\\u2028\\u2029]";
var _prefix = new RegExp("^" + sWhiteSpace + "+");
var _suffix = new RegExp(sWhiteSpace + "+$");
return function () {
return this.replace(_prefix, "").replace(_suffix, "");
};
}());
}
</CODE>
<MOREINFO>
<URL>https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp</URL>
<URL>http://thinkweb2.com/projects/prototype/whitespace-deviations/</URL>
<URL>https://developer.mozilla.org/en/Firefox_3.1_for_developers</URL>
<URL>http://docs.sun.com/source/816-6408-10/regexp.htm</URL>
<URL>http://msdn.microsoft.com/en-us/library/6wzad2b2%28VS.85%29.aspx</URL>
<URL>http://groups.google.com/group/comp.lang.javascript/browse_frm/thread/c7010139217600c3/31092c5eb99625d0?#31092c5eb99625d0</URL>
<URL>http://unicode.org/Public/UNIDATA/PropList.txt</URL>
</MOREINFO>
</CONTENT>
</CONTENT>
You can’t perform that action at this time.