📖 JavaScript Strings, Numbers and Dates
Strings
Strings are groups of characters used to make words and sentences. They are encased in quotes. Numbers, or more specifically numerals, can be a part of a string if they are encased in quotes or if they are added to strings. JavaScript is a dynamic language that will convert some data types based on their context. While strings are primitive data types, JavaScript treats them like objects to access their properties and methods.
- String Object
- an object containing a text string
- Length Property
- a property that contains the number of characters in the string
Example
<script>
var string = "Hello World!";
var len = string.length;
// string.length; returns a value of 12
</script>
Method | Description |
---|---|
string.toUpperCase() | returns the string converted to all uppercase characters |
string.toLowerCase() | returns the string converted to all lowercase characters |
string.charAt(i) | returns the ith character from string (note: 0 based array) |
string.charCodeAt(i) | returns the ith character's Unicode value from string |
string.concat(str2) | concatenates string with str2 (appends str2 at the end of string) |
string.indexOf(str, start) | returns the index of the first character of the text that matches str beginning at the start index number in string. Default for start is 0. |
string.lastIndexOf(str,start) | returns the index of the last occurence of the text that matches str beginning at the start index number in string. Default for start is 0. |
string.slice(start, end) | extracts a substring from string, beginning at the start index and ending at the end index. Default for end is the last character in the string. |
string.split(str) | splits string into an array of string characters at each occurrence of str. |
string.substr(start, length) | returns a substring from string starting at the start index and continuing for length characters. If length is not specified, continues to the last character of string. |
string.substring(start, end) | returns a substring from string starting at the start index and continuing to the end index. If end is not specified, continues to the last character of string. |
/* function converts the user name into all caps and pig latin */
function pigLatin(userName) {
var pigName = userName.toUpperCase();
var firstLetter = pigName.charAt(0);
pigName = pigName.slice(1,pigName.length);
pigName = pigName + firstLetter + "ay";
return pigName;
}
Numbers
Function | Description |
---|---|
isNaN(n) | Determines whether a value n is an illegal number. |
parseFloat(s) | Parses a string s and returns a floating point number. |
parseInt(s) | Parses a string s and returns an integer. |
Number(v) | Converts an object's value v to a number. |
String(v) | Converts an object's value v to a string. |
.toFixed(n) | Converts a number to a string with n decimal places. |
/* Examples */
/* Converts a number to a string with specified decimal places */
var number = 8.387;
number.toFixed(2);
/* Output = 8.39 */
/* Parses a string and returns an integer */
var integer = parseInt("8.387");
/* Output = 8 */
Math Object
- Built-in JavaScript methods that can be used in JavaScript expressions
Math.random()
returns a random number between 0 and 1. To generate a random number between 1 and a number (i.e. 10), multiply the generated random number by the maximum (10) and add 1.Math.floor(number)
returns just the integer portion of a number.- To return a random number between 1 and 20:
Math.floor(Math.random()*20)+1;
Date Object
The Date object is used to format and manipulate dates.
To create a date object:
/* creates a date object with the current date */
var date = new Date();
/* creates a date object with the specified date. */
var newDate = new Date(year, month, day, hours, minutes, seconds);
/* creates a new date object and sets date to March 21 2020 11:30:59 */
var newDate = new Date(2020, 2, 21, 11, 30, 59);
To access the properties of a date object:
/* create a date object */
var date = new Date();
/* return the hour of the day in 24 hour format */
var time = date.getHours();
/* return the numeric index of the month beginning 0 = January */
var month = date.getMonth();
The Date object has many methods. Here are some of the most common.
Method | Description |
---|---|
date.getDate() | Returns an integer number, between 1 and 31, representing the day of the month for the given date according to local time. |
date.getMonth() | Returns an integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on. |
date.getDay() | Returns an integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. |
date.getFullYear() | Returns the year of a Date object in four digit format. |
date.getHours() | Returns the hour of a Date object. |
date.getMinutes() | Returns the minutes of a Date object. |
date.getSeconds() | Returns the seconds of a Date object. |
date.getTime() | Returns the time of a Date object in number of milliseconds since the Epoch (Midnight, January 1, 1970) |
date.setDate() | Sets the date of a Date object |
date.setFullYear() | Sets the four digit year of the Date object |
date.setHours() | Sets the hours of a Date object |
date.setMinutes() | Sets the minute of a Date object |
date.setMonth() | Sets the month of a Date object |
date.setSeconds() | Sets the seconds of a Date object |
date.setTime() | Sets the time of a Date object |
date.toGMTString() | Converts a Date object to a string, set to the GMT time zone |
date.toLocaleString() | Converts a Date object to a string, set to the local time zone |
Month and day are 0 based arrays, so month 0 is January, 1 is February, etc. and day 0 is Sunday, 1 is Monday, etc. If hours, minutes and seconds are omitted, 0 is assumed.
Here are some common ways to convert the month or day index from the date methods to the month or day names. Use the value from the date method as the index number for the months or days array.
/* create an array of month names and array of day names */
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sunday', 'Monday', "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
/* access the names of the day and month from the arrays using the date from the date object */
document.write("<p>Today is " + days[date.getDay()] + " in " + months[date.getMonth()] + ".</p>");