Skip to content

Instantly share code, notes, and snippets.

@visfleet
Created April 26, 2010 06:12
Show Gist options
  • Save visfleet/379034 to your computer and use it in GitHub Desktop.
Save visfleet/379034 to your computer and use it in GitHub Desktop.
package iv {
/**
* Adds some simple String manipulation doofers that are missing from Flex standard libs
* @author grant
*
*/
public class StringHelper {
/**
* Remove all whitespace characters from the start of the string
* @param original The string to remove whitespace from
* @return The String without the leading whitespace (if any)
*
*/
public static function ltrim(original:String):String {
var regexp:RegExp = /^\s*/;
return original.replace(regexp,'');
}
/**
* Remove all whitespace characters from the end of the string
* @param original The string to remove whitespace from
* @return The String without the trailing whitespace (if any)
*
*/
public static function rtrim(original:String):String {
var regexp:RegExp = /\s*$/;
return original.replace(regexp,'');
}
/**
* Remove all whitespace characters from the start and end of the string
* @see StringUtil.Trim
* @param original The string to remove whitespace from
* @return The String without the leading and trailing whitespace (if any)
*
*/
public static function trim(original:String):String {
return ltrim(rtrim(original));
}
/**
* I don't doc nearly as often as grant does :P
* String is turned to title case, which in this instance means all word leading
* characters are upper. Please note, other characters are not affected, so you
* -may- want to use toLowerCase first.
* @param original
* @return
*
*/
public static function toTitleCase(original:String):String {
var regex:RegExp = /\b([a-z])/g
return original.replace(
regex,
matchToUpper
);
}
private static function matchToUpper(match:String,...rest):String {
return match.toUpperCase();
}
/**
* String is turned to sentence case, which in this instance means the first leadingxen
* word character is upper. Please note, other characters are not affected, so you
* -may- want to use toLowerCase first.
* @param original
* @return
*
*/
public static function toSentenceCase(original:String):String {
var regex:RegExp = /(?:^\s*)\b[a-z]/
return original.replace(
regex,
matchToUpper
);
}
public static function truncateString(source:String,length:int,elipsis:String="..."):String {
if (source.length <= length) {
return source;
}
return rtrim(source.substr(0,length)) + elipsis;
}
/**
* Takes a string, replaces indicies with spaces with underscores and removes special characters
*/
public static function sanitizeString(original:String):String {
var scharRegex:RegExp = /[^\w \xC0-\xFF]+?/ig;
var spaceRegex:RegExp = /\s+?/gi
original = original.replace(scharRegex,"");
original = original.replace(spaceRegex,"_");
return original;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment