/ Published in: ActionScript 3
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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