Return to Snippet

Revision: 31433
at September 4, 2010 21:38 by adrianparr


Initial Code
function removeExtraSpacesFromKeywords($keywords:String):String {
	var trimmedKeywords:String;
	var doubleCommaRegExp:RegExp = /,,/gi;
	var doubleSpaceRegExp:RegExp = /  /gi;
	var keywordsArray:Array = $keywords.split(",");
	for (var i=0; i<keywordsArray.length; i++) {
		keywordsArray[i] = keywordsArray[i].replace(/^\s+|\s+$/g, '');
	}
	trimmedKeywords = keywordsArray.toString();
	do {
		trimmedKeywords = trimmedKeywords.replace(doubleCommaRegExp, ",");
	} while (doubleCommaRegExp.test(trimmedKeywords));
	do {
		trimmedKeywords = trimmedKeywords.replace(doubleCommaRegExp, ",");
	} while (doubleCommaRegExp.test(trimmedKeywords));
	do {
		trimmedKeywords = trimmedKeywords.replace(doubleCommaRegExp, ",");
	} while (doubleCommaRegExp.test(trimmedKeywords));
	var firstChar:String = trimmedKeywords.substr(0, 1);
	if (firstChar == ",") {
		trimmedKeywords = trimmedKeywords.substring(1, trimmedKeywords.length);
	}
	var lastChar:String = trimmedKeywords.substr(trimmedKeywords.length-1, 1);
	if (lastChar == ",") {
		trimmedKeywords = trimmedKeywords.substring(0, trimmedKeywords.length-1);
	}
	do {
		trimmedKeywords = trimmedKeywords.replace(doubleSpaceRegExp, " ");
	} while (doubleSpaceRegExp.test(trimmedKeywords));
	do {
		trimmedKeywords = trimmedKeywords.replace(doubleSpaceRegExp, " ");
	} while (doubleSpaceRegExp.test(trimmedKeywords));
	return trimmedKeywords;
}

var keywords:String = ",,,, ,,   ,  one    ,,, ,,, , , ,, ,,,, , ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,  , ,  , ,,,,,,,,,,,,,,,,,,,, ,,,   ,  two     ,     three   ,    hello               world   ,  ,, ,,, ,,,,";
trace(keywords);
keywords = removeExtraSpacesFromKeywords(keywords);
trace(keywords);

// OUTPUT
// ,,,, ,,   ,  one    ,,, ,,, , , ,, ,,,, , ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,  , ,  , ,,,,,,,,,,,,,,,,,,,, ,,,   ,  two     ,     three   ,    hello               world   ,  ,, ,,, ,,,,
// one,two,three,hello world

Initial URL

                                

Initial Description
This function trims a string and removes empty entries in a comma delimited list, removes extra commas from the beginning and end and also remove extra space characters between words.

Initial Title
AS3 Trim a Comma Delimited String (e.g. a list of comma separated keywords entered by a user)

Initial Tags
regex, regexp

Initial Language
ActionScript 3