AS3修剪逗号分隔的字符串(例如,由用户输入的逗号分隔的关键字列表)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AS3修剪逗号分隔的字符串(例如,由用户输入的逗号分隔的关键字列表)相关的知识,希望对你有一定的参考价值。

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.
  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

以上是关于AS3修剪逗号分隔的字符串(例如,由用户输入的逗号分隔的关键字列表)的主要内容,如果未能解决你的问题,请参考以下文章

拆分逗号分隔的字符串,同时删除空格和空条目

Razor输入框逗号分隔转换

powershell 分割逗号分隔字符串和使用PowerShell修剪项目的三种不同方法

拆分由逗号分隔的 JSON blob 列表(忽略 JSON blob 中的逗号)[重复]

如何在 Oracle 中修剪逗号分隔值中的前导零?

如何从用户输入中拆分逗号分隔的字符串