Added trimBeginning(), make trim() use the other two.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@5216 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
@@ -240,20 +240,24 @@ public class StringUtil
|
|||||||
* Utility function that strips whitespace from the beginning and end of a String.
|
* Utility function that strips whitespace from the beginning and end of a String.
|
||||||
*/
|
*/
|
||||||
public static function trim (str :String) :String
|
public static function trim (str :String) :String
|
||||||
|
{
|
||||||
|
return trimEnd(trimBeginning(str));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility function that strips whitespace from the beginning of a String.
|
||||||
|
*/
|
||||||
|
public static function trimBeginning (str :String) :String
|
||||||
{
|
{
|
||||||
var startIdx :int = 0;
|
var startIdx :int = 0;
|
||||||
var endIdx :int = str.length - 1;
|
// this works because charAt() with an invalid index returns "", which is not whitespace
|
||||||
while (isWhitespace(str.charAt(startIdx))) {
|
while (isWhitespace(str.charAt(startIdx))) {
|
||||||
startIdx++;
|
startIdx++;
|
||||||
}
|
}
|
||||||
while (endIdx > startIdx && isWhitespace(str.charAt(endIdx))) {
|
|
||||||
endIdx--;
|
// TODO: is this optimization necessary? It's possible that str.slice() does the same
|
||||||
}
|
// check and just returns 'str' if it's the full length
|
||||||
if (endIdx >= startIdx) {
|
return (startIdx > 0) ? str.slice(startIdx, str.length) : str;
|
||||||
return str.slice(startIdx, endIdx + 1);
|
|
||||||
} else {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -261,12 +265,15 @@ public class StringUtil
|
|||||||
*/
|
*/
|
||||||
public static function trimEnd (str :String) :String
|
public static function trimEnd (str :String) :String
|
||||||
{
|
{
|
||||||
var endIdx :int = str.length - 1;
|
var endIdx :int = str.length;
|
||||||
while (isWhitespace(str.charAt(endIdx))) {
|
// this works because charAt() with an invalid index returns "", which is not whitespace
|
||||||
|
while (isWhitespace(str.charAt(endIdx - 1))) {
|
||||||
endIdx--;
|
endIdx--;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (endIdx >= 0 ? str.slice(0, endIdx + 1) : "");
|
// TODO: is this optimization necessary? It's possible that str.slice() does the same
|
||||||
|
// check and just returns 'str' if it's the full length
|
||||||
|
return (endIdx < str.length) ? str.slice(0, endIdx) : str;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user