我试图弄清楚如何创建一个函数来“突出显示”给定字符串的子字符串。理想情况下,该函数将采用 3 个参数:Haystack String、Search/Needle String 和 New Format。
这是我到目前为止所拥有的:
/*
* Replaces all occurances of one series of characters with another series of characters in correct TextFormat
*
* @param The haystack: TextField you are invoking the replace on.
* @param The needle: Series of characters which you plan on replacing
* @param The new format of the sub-string.
* @return null
*
* @usage <pre>StringUtility.highlight("Hello World", "World", "Michael");</pre>
*/
public static function highlight( block:TextField, search:String, appliedFormat:TextFormat ) {
var original:String = block.text;
var positions:Object = StringUtility.getPostitions( original, search );
block.setTextFormat( value.appliedFormat, positions.posStart, positions.posEnd );
}
/*
* Replaces all occurances of one series of characters with another series of characters
*
* @param The haystack: string you are invoking the getPostitions on.
* @param The needle: series of characters which you plan on measuring
* @return The object with position values
*
* @usage <pre>StringUtility.getPostitions("Hello World", "World", "Michael");</pre>
*/
public static function getPostitions(original:String, search:String) : String {
var return_string : String = "";
var start_position : Number = 0;
var end_position : Number = 0;
while (true) {
start_position = original.indexOf( search, end_position );
if ( -1 == start_position ) break;
return_string += original.substring( end_position, start_position );
return_string += search;
end_position = start_position + search.length;
}
return var positions:Object = {posStart:start_position, posEnd:end_position};
}