javascript string manipulation

54
1 CS101 Introduction to Computing Lecture 38 String Manipulations (Web Development Lecture 13)

Upload: kbhodia18

Post on 03-Oct-2015

224 views

Category:

Documents


0 download

DESCRIPTION

JavaScript and Strings

TRANSCRIPT

  • CS101 Introduction to ComputingLecture 38String Manipulations (Web Development Lecture 13)

  • During the last lecture we discussed Mathematical MethodsWe looked at the properties and methods of JavaScripts Math object

    We produced solutions for simple problems using several methods of the Math object

  • Problems & SolutionsJavaScript doesnt support drawing of graphicsHowever, crude graphics can be put together with the help of various text characters or tablesOne cannot write a character at a random location on the screen using JavaScriptInstead, the graph has to be drawn from top to bottom, one row at a time just like when regular text is written to a document

  • Mathematical Functions in JavaScriptIn addition to the simple arithmetic operations (e.g. +, *, etc.) JavaScript supports several advanced mathematical operations as well

    Notationaly, these functions are accessed by referring to various methods of the Math object

    Moreover, this object also contains several useful mathematical constants as its properties

    This object has no use, but of a placeholder

  • PropertiesMath.PIMath.EMath.LN2Math.LN10Math.LOG2EMath.LOG10EMath.SQRT2 Math.SQRT1_2Note the CAPITAL lettering of all properties

  • Methodsrandom( )sin( r )cos( r ) tan( r )asin( x )acos( x ) atan( x ) atan2( x, y )max( x, y )max( x, y )round( x )floor( x )ceil( x ) exp( x )log( x )abs( x )sqrt( x )pow( x, y )

  • sin( r ), cos( r ), tan( r )Standard trigonometric functions

    Returns the sine, cosine or tangent of r,where r is specified in radians

    EXAMPLEdocument.write( Math.cos( Math.PI / 4 ) )0.7071067811865476

  • asin( x ), acos( x ), atan( x )Standard inverse-trigonometric functions

    Returns the arcsine, arccosine or arctangent of rin radians

    EXAMPLEdocument.write( Math.asin( 1 ) )1.5707963267948965

  • Returns the square root of xsqrt( x )0.5 0.7071Returns x raised to the power ypow( x, y )2, 32 4294967296

  • Returns Math.E raised to the power xexp( x )1 2.718281Returns the the natural logarithm of xlog( x )Math.E 1

  • ceil( x )Returns integer nearest to xReturns largest integer that is less than or equal to xReturns smallest integer that is greater than or equal to xfloor( x )round( x )1.1 112.5 13-13.9 -141.1 112.5 12-13.9 -141.1 212.5 13-13.9 -13

  • Returns the absolute value of xabs( x )1.1 1.1-12.5 12.50 0

  • Returns the smaller of x and ymin( x, y )2, 4 2-12, -5 -12Returns the larger of x and ymax( x, y )2, 4 4-12, -5 -5

  • random( )Returns a randomly-selected, floating-point number between 0 and 1

    EXAMPLEdocument.write( Math.random( ) )0.9601111965589273

  • random( ): ExampleDesign a Web page that displays the result of the rolling of a 6-sided die on user command

  • Todays Goal(String Manipulation)To become familiar with methods used for manipulating strings

    To become able to solve simple problems involving strings

  • String Manipulation ExamplesCombine these words into a sentence i.e. take these strings and concatenate them into oneBreak this string into smaller onesConvert this string into upper caseSee if a particular character exists in a stringFind the length of a stringConvert this string into a number

  • String Manipulation in JavaScriptIn addition to the concatenation operator (+) JavaScript supports several advanced string operations as well

    Notationaly, these functions are accessed by referring to various methods of the String object

    Moreover, this object also contains the length property

  • Examplename = BHOLA ;document.write( The length of the string name is , name.length ) ;The length of the string name is 5

  • Let us now revisit an example that we first discussed in the 18th lecture

    Let us see how we put the length property of a string to good use

  • Send an eMailfunction checkForm( ) { }

  • function checkForm( ) { if( document.sendEmail.sender.value.length < 1 ) {window.alert(Empty From field! Please correct ) ;}}This is a string

  • Other Uses of the length PropertyTo restrict the length of login name or password to specified bounds, i.e. no less than 4 and no more than 8 characters

    ???

  • String MethodsFORMATstring.methodName( )

    EXAMPLE:name = Bhola ;document.write( name.toUpperCase( ) ) ;document.write( name.bold( ) ) ;BHOLABhola

  • Two Types of String MethodsHTML Shortcuts

    All Others

  • String Methods: HTML Shortcutsbold( )italics( )strike( )sub( )sup( )big( )small( )fontsize( n )fixed( )fontcolor( color )link( URL )

  • big( ), small( ), fontsize( n )person = "Bhola" ;document.write( person ) ;document.write( person.big( ) ) ;document.write( person.small( ) ) ;document.write( person.fontsize( 1 ) ) ;document.write( person.fontsize( 7 ) ) ;

    BholaBholaBholaBholaBhola

  • sub( ), sup( )person = "Bhola" ;document.write( name ) ;document.write( name.sub( ) ) ;document.write( name ) ; document.write( name.sup( ) ) ;

    BholaBholaBholaBhola

  • bold( ), italics( ), strike( )name = "Bhola" ;document.write( name ) ;document.write( name.bold( ) ) ;document.write( name.italics( ) ) ;document.write( name.strike( 1 ) ) ;

  • fixed( ), fontcolor( color )person = "Bhola" ;document.write( person ) ;document.write( person.fixed( ) ) ;document.write( person.fontcolor( blue ) ) ;document.write( person.fontcolor( orange ) ) ;

    BholaBholaBholaBhola

  • link( URL )hotel = "Bhola Continental" ;document.write( hotel ) ;document.write( hotel.link(http://www.bholacontinental.com ) ) ;

    Bhola ContinentalBhola Continental

  • What was common among all those methods that we just discussed?

  • big( ) small( ) sub( ) sup( ) bold( ) italics( ) strike( )

  • fontsize( n )

    fontcolor( color )

    fixed( ) link( URL )

  • String Methods: All Otherssplit( delimiter )toLowerCase( )toUpperCase( )charAt( n )substring( n, m )indexOf( substring, n )lastIndexOf( substring, n )

  • toLowerCase( ), toUpperCase( )person = "Bhola" ;document.write( person ) ;document.write( person.toLowerCase( ) ) ;document.write( person.toUpperCase( ) ) ;

    BholabholaBHOLA

  • charAt( n )Returns a string containing the character at position n (the position of the 1st character is 0)mister = "Bhola" ;document.write( mister ) ;document.write( mister.charAt( 0 ) ) ;document.write( mister.charAt( 8 ) ) ;document.write( mister.charAt( 2 ) ) ;

    Bo

  • substring( n, m )Returns a string containing characters copied from positions n to m - 1s = "Bhola" ;document.write( s.substring( 1, 3 ) ) ;document.write( s.substring( 0, s.length ) ) ;hoBhola

  • indexOf( substring, n ) Returns the position of the first occurrence of substring that appears on or after the nth position, if any, or -1 if none is founds = "Bhola" ;document.write( s.indexOf( ola, 1 ) ) ;document.write( s.indexOf( z, 3 ) ) ;2-1

  • lastIndexOf( substring, n ) Returns the position of the last occurrence of substring that appears on or before the nth position, if any, or -1 if none is found

    s = "Bhola" ;document.write( s.lastIndexOf( ola, 5 ) ) ;document.write( s.lastIndexOf( b, 0 ) ) ;2-1

  • split( delimiter ) Returns an array of strings, created by splitting string into substrings, at delimiter boundaries

    s = "Hello: I must be going!" ;a = new Array( 5 ) ;b = new Array( 5 ) ;a = s.split( " " ) ;b = s.split( "e" ) ;document.write( "" ) ;for( k = 0; k < 5; k = k + 1 )document.write( "", a[ k ], "", b[ k ], "" ) ;document.write( "" ) ;Hello:HIllo: I must bmustgoing!beundefinedgoing!undefined

  • Automatic Conversion to Strings Whenever a non-string is used where JavaScript is expecting a string, it converts that non-string into a stringExample:The document.write( ) method expects a string (or several strings, separated by commas) as its argumentWhen a number or a Boolean is passed as an argument to this method, JavaScript automatically converts it into a string before writing it onto the document

  • The + OperatorWhen + is used with numeric operands, it adds them

    When it is used with string operands, it concatenates them

    When one operand is a string, and the other is not, the non-string will first be converted to a string and then the two strings will be concatenated

  • The + Operator: Examplesdocument.write( 2 + Math.PI ) ;document.write( "2" + "3" ) ;document.write( "2" + Math.PI ) ;document.write( "Yes" + false ) ;5.1415926535897932323.141592653589793Yesfalse

  • Strings In Mathematical ExpressionsWhen a string is used in a mathematical context, if appropriate, JavaScript first converts it into a number. Otherwise, a NaN is the result document.write( "2" * Math.PI ) ;document.write( "Yes" ^ 43 ) ;NaN6.283185307179586

  • The toString MethodExplicit conversion to a stringEXAMPLE:Convert 100.553478 into a currency format

    a = 100.553478 ;b = a.toString( ) ;decimalPos = b.indexOf( ".", 0 ) ;c = b.substring( 0, decimalPos + 3 ) ;document.write( c ) ;100.55

  • Conversion from StringsparseInt( ) and parseFloat( ) methods

  • 90009009000900

  • function calc( ) {document.myForm.total.value =document.myForm.salary.value +document.myForm.bonus.value ;}

  • function calc( ) {document.myForm.total.value =parseFloat( document.myForm.salary.value ) +parseFloat( document.myForm.bonus.value ) ;}Why not use parseInt( ) here?

  • During Todays Lecture We become familiar with methods used for manipulating strings

    We became able to solve simple problems involving strings

  • Next (the 14th) Web Dev Lecture:Images & AnimationTo become able to add and manipulate images and animations to a Web page