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
searchsubstring.-
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)) ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access