Computers ad Scietific Thikig David Reed, Creighto Uiversity Chapter 15 JavaScript Strigs 1 Strigs as Objects so far, your iteractive Web pages have maipulated strigs i simple ways use text box to iput a word or phrase store that text i a (strig) variable icorporate the text i a message, possibly usig + to cocateate strigs are differet from umbers ad Booleas i that they are objects a software object is a uit of code that ecapsulates both data ad operatios that ca be performed o that data a strig is a software object that models words ad phrases data: a sequece of characters, eclosed i quotes operatios iclude: make upper case, make lower case, determie the umber of characters, access a particular character, search for a particular character, 2 1
Object-Orieted Programmig objects are fudametal i the domiat approach to developig software systems: object-orieted programmig (OOP) OOP ecourages programmers to desig programs aroud software objects p the programmer idetifies the real-world objects ivolved i a system (e.g., for a bakig program: bak accout, customer, teller, ) p the desigs ad builds software objects to model these real-world objects OOP is effective for maagig large systems, sice idividual objects ca be assiged to differet teams ad developed idepedetly OOP also supports code reuse, sice the same or similar objects ca be combied i differet ways to solve differet kids of problems example: a doorbell butto has physical compoets/properties: color, shape, label, has fuctioality: whe you press the butto, the bell rigs a HTML butto is a software object that models a real-world butto has physical compoets/properties: color, shape, label, has fuctioality: whe you click o the butto, JavaScript code is executed 3 Properties ad Methods usig object-orieted termiology, the characteristics of a object are called properties p e.g., a strig object has a legth property that idetifies the umber of characters i the strig the operatios that ca be performed o the strig are called methods p e.g., the tolowercase method makes a copy of the strig with all uppercase letters coverted to lower-case properties ad methods are ot ew cocepts a property is a special kid of a variable (it stores a value) a method is a special kid of fuctio (it performs some actio) what is special is that they are associated with (or "belog to") a object e.g., each strig object will have its ow variable to stores it legth to access a object property, specify: object ame, a period, property ame str1 = 'foo'; str2 = 'Hi there'; le1 = str1.legth; le2 = str2.legth; 4 2
Properties ad Methods similarly, to call a method: object ame, period, method call e.g., str.tolowercase() calls the tolowercase method o str (which returs a lowercase copy of the strig) e.g., str.touppercase() calls the touppercase method o str (which returs a uppercase copy of the strig) ote: the tolowercase ad touppercase methods do ot chage the strig object they are called o (oly a assigmet ca do that!) istead, they retur modified copies of the strig 5 Strig Maipulatio Page 6 3
Commo Strig Methods useful methods exist that allow programmers to access ad maipulate idividual compoets of a strig compoets are idetifiable via idices, or umbers that correspod to the order i which idividual characters occur i a strig idices are assiged i ascedig order from left to right, so that the first character i the strig is at idex 0 the charat method provides access to a sigle character withi the strig it takes a idex as a iput ad returs the character at that particular idex word = 'foo'; ch = word.charat(0); // ASSIGNS ch = 'f' the substrig method provides access to a etire sequece of characters withi the strig it takes two umbers as iputs, represetig the startig (iclusive) ad edig (exclusive) idices of the substrig, ad returs the substrig word = 'foo'; sub = word.substrig(1, 3); // ASSIGNS sub = 'oo' 7 Strig Access/Cocateatio recall: the cocateatio operator (+) ca joi strigs together assumig the variable word stores a strig value, what affect would the followig assigmet have? word = word.charat(0) + word.substrig(1, word.legth); the followig fuctio takes a strig as iput ad uses strig method calls to create (ad retur) a capitalized versio of that strig 8 4
Searchig Strigs the search method traverses a strig i order to locate a give character or substrig it takes a character or strig as iput ad returs the idex at which the character or strig first occurs (or -1 if ot foud) str = 'baaa'; um1 = str.search(''); // ASSIGNS um1 = 2 sice the character // '' first occurs at idex 2 um2 = str.search('aa'); // ASSIGNS um2 = 1 sice the strig // 'aa' first occurs at idex 1 um3 = str.search('z'); // ASSIGNS um3 = -1 sice the character // 'z' does ot occur aywhere simple applicatio: determie whether a strig is a sigle word or a phrase if the strig cotais o spaces, the call str.search(' ') will retur -1, idicatig that the strig value cosists of a sigle word if str.search(' ') returs a oegative value, the the presece of spaces sigifies a phrase cotaiig multiple words 9 Geeral Searches there are times whe you wat to search for a type of character, rather tha a specific value example: covertig a word ito Pig Lati if a word cotais o vowels or begis with a vowel, the characters 'way' are appeded to the ed of the word th à thway apple à appleway if a word begis with a cosoat, its iitial sequece of cosoats is shifted to the ed of the word followed by 'ay' baaa à aaabay cherry à errychay i order to distiguish betwee these two cases, must search for the first vowel p the, use the substrig method to break the strig ito parts ad the + operator to put the pieces back together (with 'ay') cherry à erry + ch + ay = errychay 10 5
Geeral Searches rather tha havig to search for vowels idividually, a etire class of characters ca be specified usig /[... ]/ 11 Strigs ad Repetitio some tasks ivolve repeatedly performig the same operatios to accomplish such tasks, we ca combie while loops with strig methods such as charat ad search example: a while loop used to access ad process each character i a strig the characters that comprise the strig are cocateated oe-by-oe oto aother strig, resultig i a exact copy 12 6
Example: Substitutio Ciphers a substitutio cipher is a code for ecryptig/decryptig messages oe letter of the alphabet is substituted for aother i the message Atbash cipher (500 B.C.) was used by Hebrew scribes Caesar cipher (50-60 B.C.) was used by Julius Caesar ABC à ZYX ABC à DEF HELLO à SVOOL HELLO à KHOOR substitutio ciphers are easy to uderstad ad use 26! 4 x 10 26 possible substitutio keys 13 Text Areas a text area is similar to a text box but it ca cotai ay umber of text lies geeral form of a text area elemet: <textarea id='area_id' rows=num_rows cols=num_cols> INITIAL_TEXT </textarea> the ID attribute gives the elemet a idetifier so that it ca be refereced the ROWS attribute specifies the height (umber of text lies) of the area the COLS attribute specifies the width (umber of characters) of the area ulike a text box, opeig ad closig tags are used to defie a text area ay text appearig betwee the tags will be the iitial text i the text area otherwise, the cotets of a text area are accessed/assiged i the same way documet.getelemetbyid('area_id').value 14 7
Ecodig a message pseudocode: for as may letters as there are i the message get the ext character i the message fid its positio i the alphabet fid the correspodig letter i the key use that letter to ecode the curret letter i the message 15 8