Replace all by Split/RegEx in ActionScript

Categories: Flex; Tagged with: ; @ December 6th, 2011 20:53

Problem

We need replace all method.

Solution

use RegEx or split&jion;

Detailed explanation

We can use the following two methods:

	private function testFlexStringReplaceAll():void {
		var strSource:String = "Li_guo_Liang.com";
		trace(strSource + " - " + replaceAllBySplit(strSource, "_", ""));
		trace(strSource + " - " + replaceAllByRegex(strSource, "_", ""));
	}

	/**
	 * Repalce all by split and join;
	 */
	public static function replaceAllBySplit(strSource:String, strReplaceFrom:String, strRepalceTo:String):String {
		return strSource == null ? null : strSource.split(strReplaceFrom).join(strRepalceTo);
	}
	
	/**
	 * Replace all by RegEx;
	 */
	public static function replaceAllByRegex(strSource:String, strReplaceFrom:String, strRepalceTo:String):String {
		return strSource == null ? null : strSource.replace(new RegExp(strReplaceFrom, 'g'), strRepalceTo);
	}

TraceLog:

Li_guo_Liang.com – LiguoLiang.com
Li_guo_Liang.com – LiguoLiang.com



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.