COM271, Week 10
Number and String Objects
Syllabus | Table of Pages | Assignments | References and Useful Links
Number
See W3Schools Number Object for full list of all properties and methods: www.w3schools.com/jsref/jsref_obj_number.asp
The number ( ) object corresponds to the primitive number data type. Its toString
( ) method converts a number into a character string. The method toFixed restricts a number to a set number of decimal places:
var pi = 3.14159;
var n=pi.toFixed(2);
returns n=3.14.
String
See W3Schools String Object of properties and methods: www.w3schools.com/jsref/jsref_obj_string.asp
See also the W3Schools tutorial for string: http://www.w3schools.com/js/js_obj_string.asp
The String object contains all the methods for string manipulation and examination, substring extraction, and conversion to marked-up HTML . The only String ( ) property is string.length. No method operates on the string in place. You must assign the results of a string method back to the string to effect a change in the string. Examples of string methods:
- toUpperCase ( ) and toLowerCase ( ) return a string with altered case.
- charAt ( ) returns a character by position, facilitating examination of strings; charCodeAt ( ) returns the numerial unicode value of a character by position.
- indexOf ( ) returns the index of the first occurrence of the argument in a string. e.g., "JavaScript".indexOf("S") returns 4; -1 is returned if the argument is not found in the string.
- lastIndexOf ( ) returns the index of the last occurence of the argument in a string.
- substring (startIndex, endIndex) is used to extract substrings, beginning with index startIndex and ending with endIndex. Slice ( ) is similar, but permits negative arguments, which are treated as offsets from the end of the string.
Manipulating strings: Concatenation with the + operator or the String.concat( ) method joins strings. Split (stringArg) returns an array of strings based on a delimiter stringArg (e.g., "," for a comma delimiter).
Escaping characters
To insert special characters into a string, they must be preceeded by a back slash ( \ ). These "escaped" characters include
- \' single quote
- \" double quote
- \\ backslash
- \n new line
- \r carriage return (permits overprinting)
- \t tab
- \b backspace (overprint one character)