|
The main
purpose of RegExp object is to search and match string patterns in another
string. A Match object is created each time the RegExp object finds a match.
Pattern string matching is typically used for string validation.
Below are
examples of xCommerce Custom Scripts that use RegExp to do a string search and
replace.
Examples:
////////////////////////////////////////////////////////
// xCommerce Custom ECMAScript Samples //
// Copyright(c) 1999-2001 SilverStream Software Inc. //
// All Rights Reserved. //
////////////////////////////////////////////////////////
/*********************************************************************************/
// functionname: testReplace(Str, strPattern, strReplaceWith)
// Description: Replaces the strPattern in Str with the strReplaceWith
// Str: is required, a string
// strPattern: is required, a string
// strReplaceWith: is required, a string
// Returns: Returns the new value of Str
/*********************************************************************************/
function testReplace(Str, strPattern, strReplaceWith)
{
var
sPat = new RegExp(strPattern);
sPat.global = true;
sPat.ignoreCase = true;
var newStr = String(Str).replace(sPat, strReplaceWith);
return newStr;
}
/*********************************************************************************/
// functionname: testSearch(Str, strPattern)
// Description: Finds the position of the first occurence of the strPattern in
the Str
// Str: is required, a string
// strPattern: is required, a string
// Returns: Returns the position of the first occurence of the strPattern in the
Str
/*********************************************************************************/
function testSearch(Str, strPattern)
{
var sPosition = String(Str).search(RegExp(strPattern));
return sPosition;
}
Specifics
about RegExp:
1. A new
RegExp object is created when either search or replace needs to be done.
2. There are
two parameters in replace.
a. global replace can be turned on by setting the property 'global' to true.
b. case sensitive search/replace can be performed by setting the property 'ignorecase'
to true.
3. xCommerce
uses Unix syntax for regular expressions. So any pattern which follows Unix
regular expression patterns will work here.
|