9.9. Removing and Replacing Characters

Problem

You want to remove characters from a string and optionally replace them.

Solution

Create a custom String.sim pleReplace( ) method. Alternatively, for replacing patterns, use the String.rep lace( ) method included in RegExp.as.

Discussion

ActionScript does not provide a native method that replaces substrings within a string. Therefore, you must use a custom method to do so. If you want to replace instances of a specific substring, you can create a custom simpleReplace( ) method for the String class. This method should accept up to three parameters:

search

The substring you want to find and replace.

replace

The value with which to replace the occurrences of the search substring.

matchCase

If true, the method performs a case-sensitive search. Otherwise, it performs a case-insensitive search.

Here is our custom String.simpleReplace( ) method:

String.prototype.simpleReplace = function (search, replace, working) {

  // temp stores the string value with the replaced substrings.
  var temp;

  // working holds the value of the string.
  var working = this;

  // Perform a case-insensitive search if so directed.
  if (!matchCase) {
    working = this.toLowerCase(  );
    search = search.toLowerCase(  );
  }

  // searchIndex holds the starting index of a matches. startIndex stores the value // of the index after the replaced substring. var searchIndex = -1; var startIndex = 0; // Find each match to the search substring. while ((searchIndex = working.indexOf(search, startIndex)) ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.