O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Removing and Replacing Characters and Words Using Patterns

Problem

You want to remove characters from a string that matches a regex, or you want to replace pattern matches with a different substring.

Solution

Use the String.replace() method.

Discussion

The String.replace() method (see Recipe 12.7) allows you to use a string pattern to replace characters and words. Instead of using a string to define the pattern to replace, a more powerful approach is to use a regular expression.

You’ll recall from Recipe 12.7 that the replace() method takes two parameters:

pattern

The substring or regular expression you want to find and replace.

replace

The value with which to replace each pattern match. This value is typically a string, but can also be a function that returns a string; this is particularly useful when pattern is a regular expression.

Using the replace() method is the same as what you’re already familiar with, except instead of using a string pattern, you use a regex. Remember that replace() does not modify the original string, so make sure you use the string returned by replace() to work with the result:

var example:String = "<p>A string with <b>HTML</b> in it</p>";

// Replace the HTML by using a non-greedy global regex, using the empty
// string as the replacement substring for every match to the pattern.
example = example.replace( /<.*?>/g, "" );

// Displays: A string with HTML in it
trace( example );

The preceding code demonstrates how to remove HTML tags within a string. The use of a ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required