World Wide Web Programming - Welcome to the CS-465 Home Site

LANGUAGE=JavaScript onclick="return butStopTimer_onclick()">. . . ... availWidth = document.body.scrollWidth / 10;.
232KB taille 3 téléchargements 237 vues
World Wide Web Programming 16 - String Manipulation

Basic methods we already used length ‹ charAt() and charCodeAt() ‹ indexOf() and lastIndexOf() ‹ substr() and substring() ‹ toUpperCase() and toLowerCase() ‹

The split() method Split will be the equivalent of explode in PHP ‹ It takes a string, a delimiter and creates an array ‹ BE CAREFULL if you have the string “A,B,C,” and split(‘,’) it will give you 4 entries “A”, “B”, “C” and “” ‹

Reversing the order of a text ‹

function splitAndReverseText(textAreaControl) { var textToSplit = textAreaControl.value; var textArray = textToSplit.split('\r\n'); var numberOfParts = 0; numberOfParts = textArray.length; var reversedString = ""; var indexCount; for (indexCount = numberOfParts - 1; indexCount >= 0; indexCount--) { reversedString = reversedString + textArray[indexCount]; if (indexCount > 0) { reversedString = reversedString + "\r\n"; } } }

textAreaControl.value = reversedString;

Other methods myString.replace(“May”, “June”); ‹ myString.search(“Java”); ‹

• Return string’s position or -1 if not found • It’s like indexOf except that search accepts regular expressions ‹

myString.match(“2000”); • Creates an array with all the matches, only useful with regular expressions

Using the UTC ‹

‹

‹ ‹

UTC is the Coordinated Universal Time, implemented in 1964, previously known as GMT (Greenwich Mean Time) Basically if it’s midnight at Greenwich (London) it will be 7pm in Hoboken and 1am in Alicante (Spain) JavaScript supports the UTC Works similar than with a normal Date

Example ‹

<SCRIPT LANGUAGE = JavaScript> var localTime = new Date();

UTC Time is <SCRIPT LANGUAGE = JavaScript> document.write(localTime.toUTCString());

Local Time is <SCRIPT LANGUAGE = JavaScript> document.write(localTime.toLocaleString());

Time Zone Offset is <SCRIPT LANGUAGE = JavaScript> document.write(localTime.getTimezoneOffset());



Setting and Getting the UTC Date and Time ‹ ‹ ‹ ‹ ‹ ‹ ‹ ‹

setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() To “get” just replace setUTC… by getUTC…

World Time Converter Check http://cs465.free.fr/files/samples/dat e/ ‹ Open the TimeConverter1 ‹

One shot timer ‹

<SCRIPT LANGUAGE=JavaScript> var timerID; function window_onload() { timerID = setTimeout("alert('Times Up!')",3000); alert("Timer Set"); } function butStopTimer_onclick() { clearTimeout(timerID); alert("Timer has been cleared"); }

Example: Banner Change ‹

<SCRIPT LANGUAGE=JavaScript> var currentImgNumber = 1; var numberOfImages = 3; function window_onload() { setTimeout("switchImage()",3000); } function switchImage() { currentImgNumber++; document.imgAdvert.src = "AdvertImage" + currentImgNumber + ".jpg"; if (currentImgNumber < numberOfImages) setTimeout("switchImage()",3000); }

{

}

Setting a regular timer var myTimerID = setInterval(“myFunction()”, 5000); ‹ This will run myFunction() every 5 seconds ‹ You can clear the timer with ‹

• clearInterval(myTimerID);

Scrolling Status Bar ‹

<SCRIPT LANGUAGE = JavaScript> var message = “Welcome to CS465"; var startChar = 0; var maxLength; maxLength; function window_onload() window_onload() { var availWidth = 0; var spaces = ""; if (navigator.appName (navigator.appName == "Netscape") { availWidth = window.innerWidth / 10; } else { availWidth = document.body.scrollWidth / 10; } while (availWidth (availWidth > 0) { spaces = spaces + " "; availWidth-availWidth--;; } message = spaces + message; maxLength = message.length - 1; setInterval("scrollMessage()",65); } function scrollMessage() scrollMessage() { window.status = message.substring(startChar); message.substring(startChar); startChar++; startChar++; if (startChar (startChar == maxLength) maxLength) { startChar = 0; } }

Beginning Regular Expressions We use the RegExp object ‹ We can create a new RegExp by doing ‹

• var myRegExp = /\b’|’\b/; • var myRegExp = new RegExp(“\\b’|’\\b”);

Simple Regular Expressions var myString = “Paul, Paula, Pauline, paul, Paul”; var myRegExp = /Paul/; myString = myString.replace(myRegExp, “Ringo”) ‹ This would change the string into Ringo, Paula, Pauline, paul, Paul ‹

How to match more? In the previous example JavaScript just replaced the first occurrence ‹ To replace all occurrences we need to add a global match ‹ var myRegExp = /Paul/gi ‹ g is a Global Match (takes all patterns) ‹ i is to set a “case-insensitive” pattern ‹

Regular Expressions special chars ‹ ‹ ‹ ‹ ‹ ‹ ‹ ‹

\d any digit 0-9 \D any character non digit \w any word character A-Za-z0-9_ \W any non-word character \s any non-white space char . a single character […] any of the characters between brackets [^…] any one character except those inside the brackets

Example ‹

function regExpIs_valid(text) { var myRegExp = /[^a-z\d ]/i; return !(myRegExp.test(text)); } function butCheckValid_onclick() { if (regExpIs_valid(document.form1.txtPhrase.value) == true) { alert("Your passphrase contains valid characters"); } else { alert("Your passphrase contains invalid characters"); } }

Repetition Characters ‹ ‹ ‹

‹ ‹ ‹ ‹

{n} match n of the previous items {n,} matches n or more of the previous item {n,m} matches at least n and at most m of the previous item ? match the previous item 0 or 1 times + match the previous item 1 or more times * match the previous item 0 or more times For example to find a number like 1-800-5555555 we can use • var myRegExp = /\d-\d{3}-\d{3}-\d{4}/;

Position Characters ‹

‹ ‹ ‹ ‹

‹ ‹

^myPattern Pattern must be at the beginning of the string or beginning of a line. (need to set RegExp.multiline = true to handle multilines) myPattern$ Pattern must be at end of line or string \b matches a word boundary \B matches a non/boundary position Example: var myString = “Hello World!, this isn’t really cool.” var myRegExp = /\b/g; myString = myString.replace(myRegExp, “|”); This would output “|Hello| |World|!, |this| |isn|’|t| |really| |cool|.” So if you just want to change Paul into something else you can set the regExp to /\bPaul\b/gi

Grouping regular expressions ‹

To match JavaScript and VBScript we can use • /\b(VB)?(Java)?Script\b/gi