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


/ Published in: ActionScript 3
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. function removeExtraSpacesFromKeywords($keywords:String):String {
  2. var trimmedKeywords:String;
  3. var doubleCommaRegExp:RegExp = /,,/gi;
  4. var doubleSpaceRegExp:RegExp = / /gi;
  5. var keywordsArray:Array = $keywords.split(",");
  6. for (var i=0; i<keywordsArray.length; i++) {
  7. keywordsArray[i] = keywordsArray[i].replace(/^\s+|\s+$/g, '');
  8. }
  9. trimmedKeywords = keywordsArray.toString();
  10. do {
  11. trimmedKeywords = trimmedKeywords.replace(doubleCommaRegExp, ",");
  12. } while (doubleCommaRegExp.test(trimmedKeywords));
  13. do {
  14. trimmedKeywords = trimmedKeywords.replace(doubleCommaRegExp, ",");
  15. } while (doubleCommaRegExp.test(trimmedKeywords));
  16. do {
  17. trimmedKeywords = trimmedKeywords.replace(doubleCommaRegExp, ",");
  18. } while (doubleCommaRegExp.test(trimmedKeywords));
  19. var firstChar:String = trimmedKeywords.substr(0, 1);
  20. if (firstChar == ",") {
  21. trimmedKeywords = trimmedKeywords.substring(1, trimmedKeywords.length);
  22. }
  23. var lastChar:String = trimmedKeywords.substr(trimmedKeywords.length-1, 1);
  24. if (lastChar == ",") {
  25. trimmedKeywords = trimmedKeywords.substring(0, trimmedKeywords.length-1);
  26. }
  27. do {
  28. trimmedKeywords = trimmedKeywords.replace(doubleSpaceRegExp, " ");
  29. } while (doubleSpaceRegExp.test(trimmedKeywords));
  30. do {
  31. trimmedKeywords = trimmedKeywords.replace(doubleSpaceRegExp, " ");
  32. } while (doubleSpaceRegExp.test(trimmedKeywords));
  33. return trimmedKeywords;
  34. }
  35.  
  36. var keywords:String = ",,,, ,, , one ,,, ,,, , , ,, ,,,, , ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, , , , , ,,,,,,,,,,,,,,,,,,,, ,,, , two , three , hello world , ,, ,,, ,,,,";
  37. trace(keywords);
  38. keywords = removeExtraSpacesFromKeywords(keywords);
  39. trace(keywords);
  40.  
  41. // OUTPUT
  42. // ,,,, ,, , one ,,, ,,, , , ,, ,,,, , ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, , , , , ,,,,,,,,,,,,,,,,,,,, ,,, , two , three , hello world , ,, ,,, ,,,,
  43. // one,two,three,hello world

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.