RegEx – search and replace

The problem is to search bit of text and replace any occurance of the searched string with something new, with RegEx class and built-in replace function of String class it is very easy.


var query:String = "volutpat";
var text:Stringt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer VOLUTPAT faucibus lectus in ultrices. Nunc semper interdum eros luctus rutrum. Praesent ipsum nibh, laoreet quis placerat ac, gravida ac libero. Duis risus nisi, malesuada nec varius quis, laoreet eu odio. Nullam nec porttitor lectus. Fusce tempor mauris eu ante imperdiet sodales. Phasellus suscipit risus id augue volutpat ut commodo lectus accumsan. Quisque dapibus dui at eros hendrerit consectetur. Quisque vel augue vel elit rutrum volutpat.";
var replace:String = "REPLACED";
var result:String;

result = text.replace(new RegExp(query, "g"), replace);

trace(result);

The result will no contain string from text variable with each occurance of query changed to value of replace. You will notice that upper cased searched word wasn’t changed – because the search was case sensitive. To make it case insensitive we need to add i to the options in the RegEx constructor (existing “g” is for global – so ALL occurances are found not just first).

result = text.replace(new RegExp(query, "gi"), replace);

Second argument of the replace method can be a function, this replacement function is very convenient if we want to do some operations before replacing, e.g. here you could change the letter-case.


function replaceFunction(...args):String
{
    var match:String = args[0];
    var index:int = args[args.length - 2];
    var fullText:String = args[args.length - 1];

    //parenthical groups
    //var pl:int = args.length - 3;
    //for (var i:int = 0; i < pl; i++) 
    //{
    //    trace("parenthical group $" + (i + 1) +"=" + args[i + 1]);
    //}
    //

    return match.toUpperCase();
}

result = text.replace(new RegExp(query, "gi"), replaceFunction);

As a note to the replacement function, the documentation doesn’t specify that this function should have arguments defined and in result it may run into ArgumentError, the solution is described here: The String’s replace method and ArgumentError: Error #1063: Argument count mismatch error

This entry was posted in actionscript, flash and tagged , , , . Bookmark the permalink.