Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

BBS: Re: JavaScript 1.2 Challenge - September 04, 1998 at 10:00:46

You are here: irt.org | BBS | Re: JavaScript 1.2 Challenge [This BBS is closed]

Posted by Jason Nugent on September 04, 1998 at 10:00:46:

In Reply to: JavaScript 1.2 Challenge posted by Vijay Jagdale on September 03, 1998 at 23:17:56:


I accept your challenge :)

You can do what you want without having to use $1 and $2. The following chunk of code illustrates the point and works just groovy.

<HTML>
<HEAD>
<SCRIPT language="JavaScript1.2">

function toUpper ()
{

var pattern = / (\w) (\w+)/; // a letter, and then more letters

var a = document.form1.text1.value.split (/\s+/g); // split the // sentence into an array of // words

for (i = 0 ; i < a.length ; i ++ )
{
var parts = a[i].match (pattern); // just a temp variable to store // the fragments in.

var firstLetter = parts[1].toUpperCase ();
var restOfWord = parts[2].toLowerCase ();

a[i] = firstLetter + restOfWord; // re-assign it back to the array // and move on

alert ("New word is " + a[i]); // let you know what the new word
// is
}

}

</HEAD>
<BODY>

<FORM NAME="form1">
<INPUT TYPE="text" NAME="text1">
<INPUT TYPE="button" onClick="toUpper ()" VALUE="To Upper Case">
</FORM>
</BODY>
</HTML>

A couple of things to notice here - the parts array which contains the fragments found in the match (you can only use $1 and $2 within the confines of a current match) contains as the first item the entire word. This is why I get my two fragments from parts[1] and parts[2], instead of parts[0] and parts[1].

By splitting the whole sentence into chunks in the beginning, you can control the fragment you are working on. This eliminates the need to worry about spaces (which your original code didn't do). With your way, you've attempted to combine the replacement of the text into the whole regular expression. This should work in theory but the way I've mentioned here is more general and can be extended to work with a whole paragraph, for example.
By the way, please excuse the way my code is written above. I hate typing in these text boxes. :)

Jason
Follow-ups:

You are here: irt.org | BBS | Re: JavaScript 1.2 Challenge [This BBS is closed]

©2018 Martin Webb