AS3 String Utils


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

This handy String Utils class was written by Ryan Matsikas at gSkinner.com
I take no credit for it.

A ZIP file containing 'StringUtils.as' can be downloaded from here ...
http://www.gskinner.com/products/downloads/AS3StringUtils.zip


Copy this code and paste it in your HTML
  1. package {
  2.  
  3. /**
  4. * String Utilities class by Ryan Matsikas, Feb 10 2006
  5. *
  6. * Visit www.gskinner.com for documentation, updates and more free code.
  7. * You may distribute this code freely, as long as this comment block remains intact.
  8. */
  9.  
  10. public class StringUtils {
  11.  
  12. /**
  13. * Returns everything after the first occurrence of the provided character in the string.
  14. *
  15. * @param p_string The string.
  16. *
  17. * @param p_begin The character or sub-string.
  18. *
  19. * @returns String
  20. *
  21. * @langversion ActionScript 3.0
  22. * @playerversion Flash 9.0
  23. * @tiptext
  24. */
  25. public static function afterFirst(p_string:String, p_char:String):String {
  26. if (p_string == null) { return ''; }
  27. var idx:int = p_string.indexOf(p_char);
  28. if (idx == -1) { return ''; }
  29. idx += p_char.length;
  30. return p_string.substr(idx);
  31. }
  32.  
  33. /**
  34. * Returns everything after the last occurence of the provided character in p_string.
  35. *
  36. * @param p_string The string.
  37. *
  38. * @param p_char The character or sub-string.
  39. *
  40. * @returns String
  41. *
  42. * @langversion ActionScript 3.0
  43. * @playerversion Flash 9.0
  44. * @tiptext
  45. */
  46. public static function afterLast(p_string:String, p_char:String):String {
  47. if (p_string == null) { return ''; }
  48. var idx:int = p_string.lastIndexOf(p_char);
  49. if (idx == -1) { return ''; }
  50. idx += p_char.length;
  51. return p_string.substr(idx);
  52. }
  53.  
  54. /**
  55. * Determines whether the specified string begins with the specified prefix.
  56. *
  57. * @param p_string The string that the prefix will be checked against.
  58. *
  59. * @param p_begin The prefix that will be tested against the string.
  60. *
  61. * @returns Boolean
  62. *
  63. * @langversion ActionScript 3.0
  64. * @playerversion Flash 9.0
  65. * @tiptext
  66. */
  67. public static function beginsWith(p_string:String, p_begin:String):Boolean {
  68. if (p_string == null) { return false; }
  69. return p_string.indexOf(p_begin) == 0;
  70. }
  71.  
  72. /**
  73. * Returns everything before the first occurrence of the provided character in the string.
  74. *
  75. * @param p_string The string.
  76. *
  77. * @param p_begin The character or sub-string.
  78. *
  79. * @returns String
  80. *
  81. * @langversion ActionScript 3.0
  82. * @playerversion Flash 9.0
  83. * @tiptext
  84. */
  85. public static function beforeFirst(p_string:String, p_char:String):String {
  86. if (p_string == null) { return ''; }
  87. var idx:int = p_string.indexOf(p_char);
  88. if (idx == -1) { return ''; }
  89. return p_string.substr(0, idx);
  90. }
  91.  
  92. /**
  93. * Returns everything before the last occurrence of the provided character in the string.
  94. *
  95. * @param p_string The string.
  96. *
  97. * @param p_begin The character or sub-string.
  98. *
  99. * @returns String
  100. *
  101. * @langversion ActionScript 3.0
  102. * @playerversion Flash 9.0
  103. * @tiptext
  104. */
  105. public static function beforeLast(p_string:String, p_char:String):String {
  106. if (p_string == null) { return ''; }
  107. var idx:int = p_string.lastIndexOf(p_char);
  108. if (idx == -1) { return ''; }
  109. return p_string.substr(0, idx);
  110. }
  111.  
  112. /**
  113. * Returns everything after the first occurance of p_start and before
  114. * the first occurrence of p_end in p_string.
  115. *
  116. * @param p_string The string.
  117. *
  118. * @param p_start The character or sub-string to use as the start index.
  119. *
  120. * @param p_end The character or sub-string to use as the end index.
  121. *
  122. * @returns String
  123. *
  124. * @langversion ActionScript 3.0
  125. * @playerversion Flash 9.0
  126. * @tiptext
  127. */
  128. public static function between(p_string:String, p_start:String, p_end:String):String {
  129. var str:String = '';
  130. if (p_string == null) { return str; }
  131. var startIdx:int = p_string.indexOf(p_start);
  132. if (startIdx != -1) {
  133. startIdx += p_start.length; // RM: should we support multiple chars? (or ++startIdx);
  134. var endIdx:int = p_string.indexOf(p_end, startIdx);
  135. if (endIdx != -1) { str = p_string.substr(startIdx, endIdx-startIdx); }
  136. }
  137. return str;
  138. }
  139.  
  140. /**
  141. * Description, Utility method that intelligently breaks up your string,
  142. * allowing you to create blocks of readable text.
  143. * This method returns you the closest possible match to the p_delim paramater,
  144. * while keeping the text length within the p_len paramter.
  145. * If a match can't be found in your specified length an '...' is added to that block,
  146. * and the blocking continues untill all the text is broken apart.
  147. *
  148. * @param p_string The string to break up.
  149. *
  150. * @param p_len Maximum length of each block of text.
  151. *
  152. * @param p_delim delimter to end text blocks on, default = '.'
  153. *
  154. * @returns Array
  155. *
  156. * @langversion ActionScript 3.0
  157. * @playerversion Flash 9.0
  158. * @tiptext
  159. */
  160. public static function block(p_string:String, p_len:uint, p_delim:String = "."):Array {
  161. var arr:Array = new Array();
  162. if (p_string == null || !contains(p_string, p_delim)) { return arr; }
  163. var chrIndex:uint = 0;
  164. var strLen:uint = p_string.length;
  165. var replPatt:RegExp = new RegExp("[^"+escapePattern(p_delim)+"]+$");
  166. while (chrIndex < strLen) {
  167. var subString:String = p_string.substr(chrIndex, p_len);
  168. if (!contains(subString, p_delim)){
  169. arr.push(truncate(subString, subString.length));
  170. chrIndex += subString.length;
  171. }
  172. subString = subString.replace(replPatt, '');
  173. arr.push(subString);
  174. chrIndex += subString.length;
  175. }
  176. return arr;
  177. }
  178.  
  179. /**
  180. * Capitallizes the first word in a string or all words..
  181. *
  182. * @param p_string The string.
  183. *
  184. * @param p_all (optional) Boolean value indicating if we should
  185. * capitalize all words or only the first.
  186. *
  187. * @returns String
  188. *
  189. * @langversion ActionScript 3.0
  190. * @playerversion Flash 9.0
  191. * @tiptext
  192. */
  193. public static function capitalize(p_string:String, ...args):String {
  194. var str:String = trimLeft(p_string);
  195. trace('capl', args[0])
  196. if (args[0] === true) { return str.replace(/^.|\b./g, _upperCase);}
  197. else { return str.replace(/(^\w)/, _upperCase); }
  198. }
  199.  
  200. /**
  201. * Determines whether the specified string contains any instances of p_char.
  202. *
  203. * @param p_string The string.
  204. *
  205. * @param p_char The character or sub-string we are looking for.
  206. *
  207. * @returns Boolean
  208. *
  209. * @langversion ActionScript 3.0
  210. * @playerversion Flash 9.0
  211. * @tiptext
  212. */
  213. public static function contains(p_string:String, p_char:String):Boolean {
  214. if (p_string == null) { return false; }
  215. return p_string.indexOf(p_char) != -1;
  216. }
  217.  
  218. /**
  219. * Determines the number of times a charactor or sub-string appears within the string.
  220. *
  221. * @param p_string The string.
  222. *
  223. * @param p_char The character or sub-string to count.
  224. *
  225. * @param p_caseSensitive (optional, default is true) A boolean flag to indicate if the
  226. * search is case sensitive.
  227. *
  228. * @returns uint
  229. *
  230. * @langversion ActionScript 3.0
  231. * @playerversion Flash 9.0
  232. * @tiptext
  233. */
  234. public static function countOf(p_string:String, p_char:String, p_caseSensitive:Boolean = true):uint {
  235. if (p_string == null) { return 0; }
  236. var char:String = escapePattern(p_char);
  237. var flags:String = (!p_caseSensitive) ? 'ig' : 'g';
  238. return p_string.match(new RegExp(char, flags)).length;
  239. }
  240.  
  241. /**
  242. * Levenshtein distance (editDistance) is a measure of the similarity between two strings,
  243. * The distance is the number of deletions, insertions, or substitutions required to
  244. * transform p_source into p_target.
  245. *
  246. * @param p_source The source string.
  247. *
  248. * @param p_target The target string.
  249. *
  250. * @returns uint
  251. *
  252. * @langversion ActionScript 3.0
  253. * @playerversion Flash 9.0
  254. * @tiptext
  255. */
  256. public static function editDistance(p_source:String, p_target:String):uint {
  257. var i:uint;
  258.  
  259. if (p_source == null) { p_source = ''; }
  260. if (p_target == null) { p_target = ''; }
  261.  
  262. if (p_source == p_target) { return 0; }
  263.  
  264. var d:Array = new Array();
  265. var cost:uint;
  266. var n:uint = p_source.length;
  267. var m:uint = p_target.length;
  268. var j:uint;
  269.  
  270. if (n == 0) { return m; }
  271. if (m == 0) { return n; }
  272.  
  273. for (i=0; i<=n; i++) { d[i] = new Array(); }
  274. for (i=0; i<=n; i++) { d[i][0] = i; }
  275. for (j=0; j<=m; j++) { d[0][j] = j; }
  276.  
  277. for (i=1; i<=n; i++) {
  278.  
  279. var s_i:String = p_source.charAt(i-1);
  280. for (j=1; j<=m; j++) {
  281.  
  282. var t_j:String = p_target.charAt(j-1);
  283.  
  284. if (s_i == t_j) { cost = 0; }
  285. else { cost = 1; }
  286.  
  287. d[i][j] = _minimum(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost);
  288. }
  289. }
  290. return d[n][m];
  291. }
  292.  
  293. /**
  294. * Determines whether the specified string ends with the specified suffix.
  295. *
  296. * @param p_string The string that the suffic will be checked against.
  297. *
  298. * @param p_end The suffix that will be tested against the string.
  299. *
  300. * @returns Boolean
  301. *
  302. * @langversion ActionScript 3.0
  303. * @playerversion Flash 9.0
  304. * @tiptext
  305. */
  306. public static function endsWith(p_string:String, p_end:String):Boolean {
  307. return p_string.lastIndexOf(p_end) == p_string.length - p_end.length;
  308. }
  309.  
  310. /**
  311. * Determines whether the specified string contains text.
  312. *
  313. * @param p_string The string to check.
  314. *
  315. * @returns Boolean
  316. *
  317. * @langversion ActionScript 3.0
  318. * @playerversion Flash 9.0
  319. * @tiptext
  320. */
  321. public static function hasText(p_string:String):Boolean {
  322. var str:String = removeExtraWhitespace(p_string);
  323. return !!str.length;
  324. }
  325.  
  326. /**
  327. * Determines whether the specified string contains any characters.
  328. *
  329. * @param p_string The string to check
  330. *
  331. * @returns Boolean
  332. *
  333. * @langversion ActionScript 3.0
  334. * @playerversion Flash 9.0
  335. * @tiptext
  336. */
  337. public static function isEmpty(p_string:String):Boolean {
  338. if (p_string == null) { return true; }
  339. return !p_string.length;
  340. }
  341.  
  342. /**
  343. * Determines whether the specified string is numeric.
  344. *
  345. * @param p_string The string.
  346. *
  347. * @returns Boolean
  348. *
  349. * @langversion ActionScript 3.0
  350. * @playerversion Flash 9.0
  351. * @tiptext
  352. */
  353. public static function isNumeric(p_string:String):Boolean {
  354. if (p_string == null) { return false; }
  355. var regx:RegExp = /^[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$/;
  356. return regx.test(p_string);
  357. }
  358.  
  359. /**
  360. * Pads p_string with specified character to a specified length from the left.
  361. *
  362. * @param p_string String to pad
  363. *
  364. * @param p_padChar Character for pad.
  365. *
  366. * @param p_length Length to pad to.
  367. *
  368. * @returns String
  369. *
  370. * @langversion ActionScript 3.0
  371. * @playerversion Flash 9.0
  372. * @tiptext
  373. */
  374. public static function padLeft(p_string:String, p_padChar:String, p_length:uint):String {
  375. var s:String = p_string;
  376. while (s.length < p_length) { s = p_padChar + s; }
  377. return s;
  378. }
  379.  
  380. /**
  381. * Pads p_string with specified character to a specified length from the right.
  382. *
  383. * @param p_string String to pad
  384. *
  385. * @param p_padChar Character for pad.
  386. *
  387. * @param p_length Length to pad to.
  388. *
  389. * @returns String
  390. *
  391. * @langversion ActionScript 3.0
  392. * @playerversion Flash 9.0
  393. * @tiptext
  394. */
  395. public static function padRight(p_string:String, p_padChar:String, p_length:uint):String {
  396. var s:String = p_string;
  397. while (s.length < p_length) { s += p_padChar; }
  398. return s;
  399. }
  400.  
  401. /**
  402. * Properly cases' the string in "sentence format".
  403. *
  404. * @param p_string The string to check
  405. *
  406. * @returns String.
  407. *
  408. * @langversion ActionScript 3.0
  409. * @playerversion Flash 9.0
  410. * @tiptext
  411. */
  412. public static function properCase(p_string:String):String {
  413. if (p_string == null) { return ''; }
  414. var str:String = p_string.toLowerCase().replace(/\b([^.?;!]+)/, capitalize);
  415. return str.replace(/\b[i]\b/, "I");
  416. }
  417.  
  418. /**
  419. * Escapes all of the characters in a string to create a friendly "quotable" sting
  420. *
  421. * @param p_string The string that will be checked for instances of remove
  422. * string
  423. *
  424. * @returns String
  425. *
  426. * @langversion ActionScript 3.0
  427. * @playerversion Flash 9.0
  428. * @tiptext
  429. */
  430. public static function quote(p_string:String):String {
  431. var regx:RegExp = /[\\"
  432. ]/g;
  433. return '"'+ p_string.replace(regx, _quote) +'"'; //"
  434. }
  435.  
  436. /**
  437. * Removes all instances of the remove string in the input string.
  438. *
  439. * @param p_string The string that will be checked for instances of remove
  440. * string
  441. *
  442. * @param p_remove The string that will be removed from the input string.
  443. *
  444. * @param p_caseSensitive An optional boolean indicating if the replace is case sensitive. Default is true.
  445. *
  446. * @returns String
  447. *
  448. * @langversion ActionScript 3.0
  449. * @playerversion Flash 9.0
  450. * @tiptext
  451. */
  452. public static function remove(p_string:String, p_remove:String, p_caseSensitive:Boolean = true):String {
  453. if (p_string == null) { return ''; }
  454. var rem:String = escapePattern(p_remove);
  455. var flags:String = (!p_caseSensitive) ? 'ig' : 'g';
  456. return p_string.replace(new RegExp(rem, flags), '');
  457. }
  458.  
  459. /**
  460. * Removes extraneous whitespace (extra spaces, tabs, line breaks, etc) from the
  461. * specified string.
  462. *
  463. * @param p_string The String whose extraneous whitespace will be removed.
  464. *
  465. * @returns String
  466. *
  467. * @langversion ActionScript 3.0
  468. * @playerversion Flash 9.0
  469. * @tiptext
  470. */
  471. public static function removeExtraWhitespace(p_string:String):String {
  472. if (p_string == null) { return ''; }
  473. var str:String = trim(p_string);
  474. return str.replace(/\s+/g, ' ');
  475. }
  476.  
  477. /**
  478. * Returns the specified string in reverse character order.
  479. *
  480. * @param p_string The String that will be reversed.
  481. *
  482. * @returns String
  483. *
  484. * @langversion ActionScript 3.0
  485. * @playerversion Flash 9.0
  486. * @tiptext
  487. */
  488. public static function reverse(p_string:String):String {
  489. if (p_string == null) { return ''; }
  490. return p_string.split('').reverse().join('');
  491. }
  492.  
  493. /**
  494. * Returns the specified string in reverse word order.
  495. *
  496. * @param p_string The String that will be reversed.
  497. *
  498. * @returns String
  499. *
  500. * @langversion ActionScript 3.0
  501. * @playerversion Flash 9.0
  502. * @tiptext
  503. */
  504. public static function reverseWords(p_string:String):String {
  505. if (p_string == null) { return ''; }
  506. return p_string.split(/\s+/).reverse().join('');
  507. }
  508.  
  509. /**
  510. * Determines the percentage of similiarity, based on editDistance
  511. *
  512. * @param p_source The source string.
  513. *
  514. * @param p_target The target string.
  515. *
  516. * @returns Number
  517. *
  518. * @langversion ActionScript 3.0
  519. * @playerversion Flash 9.0
  520. * @tiptext
  521. */
  522. public static function similarity(p_source:String, p_target:String):Number {
  523. var ed:uint = editDistance(p_source, p_target);
  524. var maxLen:uint = Math.max(p_source.length, p_target.length);
  525. if (maxLen == 0) { return 100; }
  526. else { return (1 - ed/maxLen) * 100; }
  527. }
  528.  
  529. /**
  530. * Remove's all < and > based tags from a string
  531. *
  532. * @param p_string The source string.
  533. *
  534. * @returns String
  535. *
  536. * @langversion ActionScript 3.0
  537. * @playerversion Flash 9.0
  538. * @tiptext
  539. */
  540. public static function stripTags(p_string:String):String {
  541. if (p_string == null) { return ''; }
  542. return p_string.replace(/<\/?[^>]+>/igm, '');
  543. }
  544.  
  545. /**
  546. * Swaps the casing of a string.
  547. *
  548. * @param p_string The source string.
  549. *
  550. * @returns String
  551. *
  552. * @langversion ActionScript 3.0
  553. * @playerversion Flash 9.0
  554. * @tiptext
  555. */
  556. public static function swapCase(p_string:String):String {
  557. if (p_string == null) { return ''; }
  558. return p_string.replace(/(\w)/, _swapCase);
  559. }
  560.  
  561. /**
  562. * Removes whitespace from the front and the end of the specified
  563. * string.
  564. *
  565. * @param p_string The String whose beginning and ending whitespace will
  566. * will be removed.
  567. *
  568. * @returns String
  569. *
  570. * @langversion ActionScript 3.0
  571. * @playerversion Flash 9.0
  572. * @tiptext
  573. */
  574. public static function trim(p_string:String):String {
  575. if (p_string == null) { return ''; }
  576. return p_string.replace(/^\s+|\s+$/g, '');
  577. }
  578.  
  579. /**
  580. * Removes whitespace from the front (left-side) of the specified string.
  581. *
  582. * @param p_string The String whose beginning whitespace will be removed.
  583. *
  584. * @returns String
  585. *
  586. * @langversion ActionScript 3.0
  587. * @playerversion Flash 9.0
  588. * @tiptext
  589. */
  590. public static function trimLeft(p_string:String):String {
  591. if (p_string == null) { return ''; }
  592. return p_string.replace(/^\s+/, '');
  593. }
  594.  
  595. /**
  596. * Removes whitespace from the end (right-side) of the specified string.
  597. *
  598. * @param p_string The String whose ending whitespace will be removed.
  599. *
  600. * @returns String .
  601. *
  602. * @langversion ActionScript 3.0
  603. * @playerversion Flash 9.0
  604. * @tiptext
  605. */
  606. public static function trimRight(p_string:String):String {
  607. if (p_string == null) { return ''; }
  608. return p_string.replace(/\s+$/, '');
  609. }
  610.  
  611. /**
  612. * Determins the number of words in a string.
  613. *
  614. * @param p_string The string.
  615. *
  616. * @returns uint
  617. *
  618. * @langversion ActionScript 3.0
  619. * @playerversion Flash 9.0
  620. * @tiptext
  621. */
  622. public static function wordCount(p_string:String):uint {
  623. if (p_string == null) { return 0; }
  624. return p_string.match(/\b\w+\b/g).length;
  625. }
  626.  
  627. /**
  628. * Returns a string truncated to a specified length with optional suffix
  629. *
  630. * @param p_string The string.
  631. *
  632. * @param p_len The length the string should be shortend to
  633. *
  634. * @param p_suffix (optional, default=...) The string to append to the end of the truncated string.
  635. *
  636. * @returns String
  637. *
  638. * @langversion ActionScript 3.0
  639. * @playerversion Flash 9.0
  640. * @tiptext
  641. */
  642. public static function truncate(p_string:String, p_len:uint, p_suffix:String = "..."):String {
  643. if (p_string == null) { return ''; }
  644. p_len -= p_suffix.length;
  645. var trunc:String = p_string;
  646. if (trunc.length > p_len) {
  647. trunc = trunc.substr(0, p_len);
  648. if (/[^\s]/.test(p_string.charAt(p_len))) {
  649. trunc = trimRight(trunc.replace(/\w+$|\s+$/, ''));
  650. }
  651. trunc += p_suffix;
  652. }
  653.  
  654. return trunc;
  655. }
  656.  
  657. /* **************************************************************** */
  658. /* These are helper methods used by some of the above methods. */
  659. /* **************************************************************** */
  660. private static function escapePattern(p_pattern:String):String {
  661. // RM: might expose this one, I've used it a few times already.
  662. return p_pattern.replace(/(\]|\[|\{|\}|\(|\)|\*|\+|\?|\.|\\)/g, '\\$1');
  663. }
  664.  
  665. private static function _minimum(a:uint, b:uint, c:uint):uint {
  666. return Math.min(a, Math.min(b, Math.min(c,a)));
  667. }
  668.  
  669. private static function _quote(p_string:String, ...args):String {
  670. switch (p_string) {
  671. case "\\":
  672. return "\\\\";
  673. case "\r":
  674. return "\\r";
  675. case "\n":
  676. return "\\n";
  677. case '"':
  678. return '\\"';
  679. default:
  680. return '';
  681. }
  682. }
  683.  
  684. private static function _upperCase(p_char:String, ...args):String {
  685. trace('cap latter ',p_char)
  686. return p_char.toUpperCase();
  687. }
  688.  
  689. private static function _swapCase(p_char:String, ...args):String {
  690. var lowChar:String = p_char.toLowerCase();
  691. var upChar:String = p_char.toUpperCase();
  692. switch (p_char) {
  693. case lowChar:
  694. return upChar;
  695. case upChar:
  696. return lowChar;
  697. default:
  698. return p_char;
  699. }
  700. }
  701.  
  702. }
  703. }

URL: http://www.gskinner.com/blog/archives/2007/04/free_extension.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.