String objects
The Sting object is used to process the characters that are already in the block
JavaScript strings
anstring (computer science)It's used to store a series of characters like "John Doe".
A string can use either single or double quotes:
-
var carname="Volvo XC60";
-
var carname='Volvo XC60';
You use the position (index) to access any character in the string:
var character=carname[7];
Strings are indexed from zero, so the first character of the string is [0], the second character is [1], and so on.
You can use quotes in strings as in the following example:
-
var answer="It's alright";
-
var answer="He is called 'Johnny'";
-
var answer='He is called "Johnny"';
Or you can use the escape character (\) in a string using quotes:
-
var answer='It\s alright;'
-
var answer="He is called \"Johnny\"";
String (String)
String (String) uses the length attribute lenght to calculate the length of a string:
Example:
-
var txt="Hello World!"
-
();
-
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
-
();
Conversion between String and Object:
an actual example
-
-
-
var str3=new String("hello,world");
-
//alert(typeof str3);// object type object
-
//string--convert to -->object--use new String (string value)
-
//object--convert to -->string--use toString() /valueoOf()--return the string of some string object
-
var str4=();
-
alert(typeof str4);
Finding a string within a string
Strings use indexOf() to locate the first occurrence of a specified character in a string:
Example.
-
var str="Hello world, welcome to the universe.";
-
var n=("welcome");
The function returns -1 if the corresponding character is not found.
The lastIndexOf() method starts at the end of the string to find the position where the string appears.
Content Matching
The match() function is used to find a specific character in a string and return that character if found.
Example.
-
var str="Hello world!";
-
(("world") + "<br>");
-
(("World") + "<br>");
-
(("world!"));
Replacement content
The replace() method replaces some characters with others in a string.
Example.
-
str="Please visit Microsoft!"
-
var n=("Microsoft","Runoob");
String Case Conversion
String case conversion using the toUpperCase() / toLowerCase() function.
Example.
-
var txt="Hello World!"; // String
-
var txt1=(); // txt1 text will be converted to upper case
-
var txt2=(); // txt2 text will be converted to lower case
String to Array
String usagesplit() function to an array.
Example.
-
txt="a,b,c,d,e" // String
-
(","); // use comma separations
-
(" "); // use space separators
-
("|"); // use vertical lines to separate
special character
Javascript You can use backslashes (\) to insert special symbols, such as apostrophes, quotation marks, and other special symbols.
Check out the JavaScript code below.
-
var txt="We are the so-called "Vikings" from the north.";
-
(txt);
In JavaScript, strings start and stop with single or double quotes. This means that the above string will be cut into: We are the so-called
The solution to the above problem can be to use backslashes to escape quotes:
-
var txt="We are the so-called \"Vikings\" from the north.";
-
(txt);
JavaScript will output the correct text string: We are the so-called "Vikings" from the north.
The following table lists other special characters, and backslashes can be used to escape special characters:
coding |
exports |
\' |
single quote |
\" |
double quote |
\\ |
tilt rod |
\n |
line feed (computing) |
\r |
enter (computer key) |
\t |
tab |
\b |
blank space |
\f |
tab window (in a web browser) |
String Object Properties
causality |
descriptive |
constructor |
A reference to the function that created the object |
length |
Length of the string |
prototype |
Allows you to add properties and methods to objects |
String Object Methods
methodologies |
descriptive |
charAt() |
Returns the character at the specified position. |
concat() |
Concatenates two or more strings and returns the new string. + |
indexOf() |
Returns the first occurrence of a specified string value in a string. |
lastIndexOf() |
Searches the string from back to front and calculates the position of the last occurrence of the returned string from the start position (0). |
match() |
Finds matches to one or more regular expressions. |
replace() |
Finds matching substrings in a string and replaces those that match the regular expression. |
split() |
Splits a string into an array of strings. |
startsWith() |
Checks if the string starts with the specified substring. |
substr() |
Extracts the specified number of characters in the string from the starting index number. |
substring() |
Extracts the character between two specified index numbers in a string. |
toLowerCase() |
Converts a string to lowercase. |
toUpperCase() |
Converts a string to uppercase. |
trim() |
Remove whitespace on both sides of the string |
toLocaleLowerCase() |
Converts strings to lowercase according to the localhost's locale. |
toLocaleUpperCase() |
Converts strings to uppercase according to the localhost's locale. |
valueOf() |
Returns the original value of a string object. |
toString() |
Returns a string. |
String object methods
String HTML wrapper method
HTML returns the content contained in the corresponding HTML tag.
The following methods are not standard, so they may not be supported under some browsers.
methodologies |
descriptive |
anchor() |
Create HTML anchors. |
big() |
Display strings in large font. <b></b> |
blink() |
Displays a flashing string. |
bold() |
Use bold to display strings. |
fixed() |
Displays strings in typewriter text. |
fontcolor() |
Displays the string using the specified color. |
fontsize() |
Displays the string using the specified size. |
italics() |
Use italics to display strings. |
link() |
Displays the string as a link. |
small() |
Use small letters to display strings. |
strike() |
Used to display strings with strikethrough. |
sub() |
Display the string as a subscript. |
sup() |
Display the string as a superscript. |
Date object
The date object is used to work with dates and times.
A Date object can be defined using the new keyword.
The following code defines a Date object named myDate
There are four ways to initialize the date
-
new Date();
-
new Date(value);
-
new Date(dateString);
-
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
Some examples of instantiating a date:
-
var today = new Date();
-
var d1 = new Date("October 13, 1975 11:13:00");
-
var d2 = new Date(79,5,24);
-
var d3 = new Date(79,5,24,11,33,0)
Setting the date
We can easily manipulate dates by using methods that target date objects.
In the following example, we set a specific date (January 14, 2010) for the Date object:
-
var myDate=new Date();
-
myDate.setFullYear(2010,0,14);
In the following example, we set the date object to a date 5 days from now:
-
var myDate=new Date();
-
myDate.setDate(myDate.getDate()+5);
Comparison of two dates
The date object can also be used to compare two dates.
The following code compares the current date to 1/14/2100:
-
var x=new Date();
-
x.setFullYear(2100,0,14);
-
var today = new Date();
-
if (x>today){
-
alert("Today is before January 14, 2100.");
-
}else{
-
alert("Today is after January 14, 2100.");
-
}
How do I format a date into a specified format?
-
Date.prototype.format = function (fmt) {
-
var o = {
-
"M+": () + 1, //months
-
"d+": (), //date
-
"h+": (), //hourly
-
"m+": (), //ingredient
-
"s+": (), //unit of angle or arc equivalent one sixtieth of a degree
-
"q+": ((() + 3) / 3), //season (sports)
-
"S": () //millisecond
-
};
-
// Get year
-
// ①
-
if (/(y+)/i.test(fmt)) {
-
fmt = fmt.replace(RegExp.$1, (() + "").substr(4 - RegExp.$1.length));
-
}
-
for (var k in o) {
-
// ②
-
if (new RegExp("(" + k + ")", "i").test(fmt)) {
-
fmt = fmt.replace(
-
RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
-
}
-
}
-
return fmt;}
-
var now = new Date();
-
var nowStr = now.format("YYYY-MM-DD"); // 2021-01-11
Date object properties
causality |
descriptive |
constructor |
Returns a reference to the Date function that created this object. |
prototype |
Gives you the ability to add properties and methods to objects. |
Date object methods
methodologies |
descriptive |
getDate() |
Returns the day of the month (1 ~ 31) from the Date object. |
getDay() |
Returns the day of the week (0 ~ 6) from the Date object. |
getFullYear() |
Returns the year in four digits from the Date object. |
getHours() |
Returns the hour (0 ~ 23) of the Date object. |
getMilliseconds() |
Returns the milliseconds (0 ~ 999) of the Date object. |
getMinutes() |
Returns the minutes (0 ~ 59) of the Date object. |
getMonth() |
Returns the month (0 ~ 11) from the Date object. |
getSeconds() |
Returns the number of seconds (0 ~ 59) of the Date object. |
getTime() |
Returns the number of milliseconds from January 1, 1970 to the present. |
getTimezoneOffset() |
Returns the minute difference between local time and Greenwich Mean Time (GMT). |
getUTCDate() |
Returns the day of the month (1 ~ 31) from the Date object according to UTC. |
getUTCDay() |
Returns the day of the week (0 ~ 6) from the Date object based on UTC. |
getUTCFullYear() |
Returns a four-digit year from the Date object based on UTC. |
getUTCHours() |
Returns the hour (0 ~ 23) of the Date object according to UTC. |
getUTCMilliseconds() |
Returns the milliseconds (0 ~ 999) of the Date object according to the UTC. |
getUTCMinutes() |
Returns the minutes (0 ~ 59) of the Date object according to UTC. |
getUTCMonth() |
Returns the month (0 ~ 11) from the Date object according to UTC. |
getUTCSeconds() |
Returns the seconds (0 ~ 59) of the Date object according to UTC. |
getYear() |
Deprecated. Please use the getFullYear() method instead. |
parse() |
Returns the number of milliseconds from midnight on January 1, 1970 to the specified date (string). |
setDate() |
Set the day of the month (1 ~ 31) in the Date object. |
setFullYear() |
Sets the year (four digits) in the Date object. |
setHours() |
Set the hour (0 ~ 23) in the Date object. |
setMilliseconds() |
Set the milliseconds (0 ~ 999) in the Date object. |
setMinutes() |
Set the minutes (0 ~ 59) in the Date object. |
setMonth() |
Set the month (0 ~ 11) in the Date object. |
setSeconds() |
Set the seconds (0 ~ 59) in the Date object. |
setTime() |
The setTime() method sets the Date object in milliseconds. |
setUTCDate() |
Sets the day of the month (1 ~ 31) in the Date object according to UTC. |
setUTCFullYear() |
Sets the year (four digits) in the Date object according to UTC. |
setUTCHours() |
Set the hour (0 ~ 23) in the Date object according to the UTC. |
setUTCMilliseconds() |
Set the milliseconds (0 ~ 999) in the Date object according to the UTC. |
setUTCMinutes() |
Set the minutes (0 ~ 59) in the Date object according to the UTC. |
setUTCMonth() |
Sets the month (0 ~ 11) in the Date object according to UTC. |
setUTCSeconds() |
The setUTCSeconds() method is used to set the seconds field for the specified time based on Universal Time (UTC). |
setYear() |
is deprecated. Please use the setFullYear() method instead. |
toDateString() |
Converts the date portion of a Date object to a string. |
toGMTString() |
is deprecated. Please use the toUTCString() method instead. |
toISOString() |
Returns the date format of the string using the ISO standard. |
toJSON() |
Returns a date string in JSON data format. |
toLocaleDateString() |
Converts the date portion of the Date object to a string based on the local time format. |
toLocaleTimeString() |
Converts the time portion of the Date object to a string based on the local time format. |
toLocaleString() |
Converts a Date object to a string based on the local time format. |
toString() |
Converts a Date object to a string. |
toTimeString() |
Converts the time portion of a Date object to a string. |
toUTCString() |
Converts a Date object to a string based on UTC. Example: var today = new Date();var UTCstring = (); |
UTC() |
Returns the number of milliseconds from January 1, 1970 to the specified date in Universal Time. |
valueOf() |
Returns the original value of the Date object. |
3. JavaScript Array (array) objects
Array objects are useful for storing a series of values using separate variable names.
What is an array?
An array object is a series of values stored using separate variable names.
If you have a set of data (e.g., car name), separate variables exist as shown below:
-
var car1="Saab";
-
var car2="Volvo";
-
var car3="BMW";
However, what if you wanted to identify a particular car from it? And not 3, but 300 cars? It would not be an easy task!
The best way to do this is with an array.
Arrays can store all values with a variable name and any value can be accessed with a variable name.
Each element in the array has its own ID so that it can be easily accessed.
Creating an Array
There are three ways to create an array.
The following code defines an array object named myCars:
1: General approach.
-
var myCars=new Array();
-
myCars[0]="Saab";
-
myCars[1]="Volvo";
-
myCars[2]="BMW";
2: Simplicity.
var myCars=new Array("Saab","Volvo","BMW");
3: Literal.
var myCars=["Saab","Volvo","BMW"];
Access to arrays
You can access a particular element by specifying the array name as well as the index number.
The following example accesses the first value of the myCars array:
var name=myCars[0];
The following example modifies the first element of the array myCars.
myCars[0]="Opel";
[0] is the first element of the array. [1] is the second element of the array.
You can have different objects in an array
All JavaScript variables are objects. Array elements are objects. Functions are objects.
So you can have different variable types in the array.
You can include object elements, functions, and arrays in an array:
-
myArray[0]=Date.now;
-
myArray[1]=myFunction;
-
myArray[2]=myCars;
Creating a new method
A prototype is a JavaScript global constructor. It constructs the properties and methods of a new Javascript object.
Example: create a new method.
-
Array.prototype.myUcase=function(){
-
for (i=0;i<this.length;i++){
-
this[i]=this[i].toUpperCase();
-
}
-
}
The above example creates a new array method for converting an array of lowercase characters to uppercase characters.
Array Properties
causality |
descriptive |
constructor |
Returns the prototype function that creates the array object. |
length |
Sets or returns the number of array elements. |
prototype |
Allows you to add properties or methods to array objects. |
Array Object Methods
methodologies |
descriptive |
concat() |
Joins two or more arrays and returns the result. |
forEach() |
The callback function is executed once for each element of the array. |
indexOf() |
Searches for an element in an array and returns the position where it is located. |
join() |
Put all the elements of an array into a string. |
lastIndexOf() |
Searches the array for an element and returns its last occurrence. |
pop() |
Deletes the last element of the array and returns the deleted element. |
push() |
Adds one or more elements to the end of the array and returns the new length. |
reverse() |
Reverses the order of the elements of the array. |
shift() |
Removes and returns the first element of the array. |
slice() |
Selects a part of the array and returns a new array. |
sort() |
Sorts the elements of an array. |
splice() |
Adds or removes elements from an array. |
toString() |
Converts an array to a string and returns the result. |
unshift() |
Adds one or more elements to the beginning of the array and returns the new length. |
valueOf() |
Returns the original value of the array object. |
Boolean objects
The Boolean object is used to convert non-Boolean values to Boolean values (true or false).
Creating Boolean Objects
Boolean objects represent two values: "true" or "false".
The following code defines a Boolean object named myBoolean:
var myBoolean=new Boolean();
If the Boolean object has no initial value or its value is.
-
//var num1=10; // 0==false in-0Numbers -true
-
//var str="hello"; // empty string==false non-empty string==true
-
var test1=null; // null==false
Boolean Object Properties
causality |
descriptive |
constructor |
Returns a reference to the Boolean function that created this object. |
prototype |
Gives you the ability to add properties and methods to objects. |
Boolean object methods
descriptive |
|
toString() |
Converts a boolean to a string and returns the result. |
valueOf() |
Returns the original value of the Boolean object. |
Math objects
The Math (arithmetic) object does what it says: performs common arithmetic tasks.
The Math object provides a variety of arithmetic types and functions. There is no need to define the object before using it.
Syntax for using Math's properties/methods
-
var x=Math.PI;
-
var y=Math.sqrt(16);
Note: The Math object does not need to be defined before using this object.
Math Object Properties
causality |
descriptive |
E |
Returns the arithmetic constant e, the base of the natural logarithm (approximately equal to 2.718). |
LN2 |
Returns the natural logarithm of 2 (approximately equal to 0.693). |
LN10 |
Returns the natural logarithm of 10 (approximately equal to 2.302). |
LOG2E |
Returns the logarithm of e in base 2 (approximately equal to 1.4426950408889634). |
LOG10E |
Returns the logarithm of e in base 10 (approximately equal to 0.434). |
PI |
Returns pi (approximately equal to 3.14159). |
SQRT1_2 |
Returns the reciprocal of the square root of 2 (which is approximately 0.707). |
SQRT2 |
Returns the square root of 2 (approximately equal to 1.414). |
Math Object Methods
methodologies |
descriptive |
abs(x) |
Returns the absolute value of x. |
acos(x) |
Returns the inverse cosine of x. |
asin(x) |
Returns the arcsine of x. |
atan(x) |
Returns the arctangent of x as a value between -PI/2 and PI/2 radians. |
atan2(y,x) |
Returns the angle (between -PI/2 and PI/2 radians) from the x-axis to the point (x,y). |
ceil(x) |
The logarithm is rounded up. |
cos(x) |
Returns the cosine of a number. |
exp(x) |
Returns the index of Ex. |
floor(x) |
Round down to x. |
log(x) |
Returns the natural logarithm of the number (with base e). |
max(x,y,z,...,n) |
Returns the highest value of x,y,z,.... ,n of the highest value. |
min(x,y,z,...,n) |
Returns the lowest value of x,y,z,.... ,n in the lowest value. |
pow(x,y) |
Returns the y-th power of x. |
random() |
Returns a random number between 0 and 1. |
round(x) |
Rounding. |
sin(x) |
Returns the sine of the number. |
sqrt(x) |
Returns the square root of a number. |
tan(x) |
Returns the tangent of the angle. |