Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

? re: 'Pattern' code

Status
Not open for further replies.

MarkJ2

Technical User
Sep 25, 2001
17
US
I was writing some code to change words into pig Latin. I wanted to change the rules abit and only change words that
started with consonants. Glowball responded to my initial question with:

var Pattern = new Object();
Pattern.vowels = /^[aeiouAEIOU]/;
var foundVowel = Pattern["vowels"].exec(theWord);
//assume var theWord holds the word
if (!foundVowel)
{//change word
}

I think I understand the first two lines: creating a new Object called Pattern and then using pattern matching, assigning the lowercase and uppercase vowels to Pattern.vowels. The third line I am confused on. I am not really sure what it is doing. Does "vowels" in brackets need to be included. And I am not familiar with exec. Does this third line of code need to be typed in exactly? When I tried the code it did not work. Could someone explain in GORY detail this third line starting with var foundVowel or offer another solution.

Thanks.
 
here is another way:
<script>
//the testing string
var theString=&quot;fgh&quot;

//the pattern (consists of first letters needed)
var thePattern = /^[aeiouAEIOU]/;

//the following returns null if this string not
//begins with one of those letters
var foundVowel = theString.match(thePattern);
//assume var theWord holds the word
if (!foundVowel) alert(&quot;wrong&quot;)
else alert(&quot;correct&quot;)
</script> Victor
 
exec() is a method of the RegExp object. It takes a string as an argument and returns null if no match is found, an array if a match is found.

So, if you have a regular expression named &quot;foo&quot; and a string named &quot;bar&quot;, you say foo.exec(bar);

The array returned is a series of strings that matched. The first being the actual matched string, and subsequent elements being strings matched from parenthesized parts of the expression in order of appearance of the left-hand parentheses.

If you say:
Code:
var RE = /^[AEIOUaeiou]/;
var ST = &quot;Apple&quot;;
var AR = RE.exec(ST);
AR now contains a one-element array whose single element resolves to &quot;A&quot;.
If you had said:
Code:
var RE = /(^[AEIOUaeiou])(\S)/;
var ST = &quot;Apple&quot;;
var AR = RE.exec(ST);
AR would contain a three-element array whose elements resolved to &quot;Ap&quot;, &quot;A&quot;, and &quot;p&quot;.

In these cases the match did not fail, however if it would have failed then null would have been returned. This allows you to test using exec() such as:
Code:
if (RE.exec(ST)) {
// do something
}
Has this cleared anything up?

-Petey
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top