TextFormatter.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Licensed Materials - Property of IBM
  3. *
  4. * IBM Cognos Products: SHARE
  5. *
  6. * (C) Copyright IBM Corp. 2016, 2018
  7. *
  8. * US Government Users Restricted Rights - Use, duplication or disclosure
  9. * restricted by GSA ADP Schedule Contract with IBM Corp.
  10. */
  11. define(['jquery'], function($) {
  12. 'use strict';
  13. var _FORMATTER = '...';
  14. var _DEFAULT_BEGIN_MAX_LENGTH = 5;
  15. var _DEFAULT_END_MAX_LENGTH = 15;
  16. var textFormatter = {};
  17. /**
  18. * middleShortenString is a function that shortens a given String from the middle.
  19. * @param {String} stringToShorten - The String to shorten
  20. * @param {int} [beginMaxLength=_DEFAULT_BEGIN_MAX_LENGTH=5] - (Optional) The position where to start the extraction.
  21. * @param {int} [endMaxLength=_DEFAULT_END_MAX_LENGTH=15] - (Optional) The position where to end the extraction.
  22. * @return {String} stringShorten - The shortened String
  23. */
  24. textFormatter.middleShortenString = function(stringToShorten, beginMaxLength, endMaxLength) {
  25. var stringShorten = stringToShorten;
  26. var beginMaxLength = (typeof beginMaxLength !== 'number') ? _DEFAULT_BEGIN_MAX_LENGTH : beginMaxLength;
  27. var endMaxLength = (typeof endMaxLength !== 'number') ? _DEFAULT_END_MAX_LENGTH : endMaxLength;
  28. if (stringToShorten.length > (beginMaxLength + endMaxLength)) {
  29. stringShorten = stringToShorten.substring(0, beginMaxLength) + _FORMATTER + stringToShorten.substring(stringToShorten.length - endMaxLength, stringToShorten.length);
  30. }
  31. return stringShorten;
  32. };
  33. /**
  34. * Transforms a string so that special characters are escaped with a leading '\'
  35. * @param {String} rawString - the unescaped raw String to be converted
  36. * @param {String[]} [specialCharactersArray] - an array of characters to escape. If this parameter
  37. * is omitted, the default ['\' , '/' ] is used.
  38. */
  39. textFormatter.escapeSpecialCharacters = function (rawString, specialCharactersArray) {
  40. var charArray = (specialCharactersArray) ? specialCharactersArray : [ '\\' , '/' ];
  41. var escapedString = '';
  42. for (var i = 0; i < rawString.length; i++) {
  43. var isSpecialCharacter = false;
  44. for (var j = 0; j < charArray.length; j++) {
  45. if (rawString.charAt(i) === charArray[j]) {
  46. escapedString += "\\";
  47. break;
  48. }
  49. }
  50. escapedString += rawString.charAt(i);
  51. }
  52. return escapedString;
  53. };
  54. return textFormatter;
  55. });