JavaScript – Strings, Math and Number Object

String Object

The string object provide several properties and methods to work around strings. The string objects can be created using new keyword. For example:

var x = new String(“Hello”);

 

The string literals are created by assigning the value to a variable. For example:

var y = “Hello”;

 

In the above example, the variable x is a string object whereas the variable y is a string literal or regular text string. The string literals can also use all the methods and properties of the String object.

 

The difference between String object and string literals is that, the string literals can be compared with another string literal. For example:

var x = “Hello”;

var y = “Hello”;

if(x === y)

alert(“Equal”);

else

alert(“Not Equal”);

 

In the above code, the alert(“Equal”) will execute. However let us see the example with String objects.

var x = new String(“Hello”);

var y = new String(“Hello”);

if(x === y)

alert(“Equal”);

else

alert(“Not Equal”);

In the above code, the alert(“Not Equal”) will be executed even though the values that the object holds are the same. This is because the string objects is an object value and not a string literal and the value might be same but the type isn’t.

 

String Property

The string object has only one property known as length. This property returns the length of the string. For example:

 

String Method

charAt() method determines which character is at a particular position.

concat() method combines the text strings.

slice() method slice out a portion of a string and returns the value that was sliced. First argument is position from which slicing should start and second argument is one greater than position where it should stop.

substr() method pulls out a portion of a string and returns the portion that is removed as a new string. First argument specifies beginning of removal and second argument specifies how may characters to remove.

substring() method works the same way as the substr() method, but allows to send arguments for beginning and ending position. First and second argument is the beginning and ending position respectively.

indexOf() method returns the position of a certain character in a string

lastIndexOf() method returns the last instance of a certain character in a string

split() method splits the string depending upon the argument as a separator.

toString() method returns a string literal value of the string.

toLowerCase() method returns the string in all lower case letters.

toUpperCase() method returns the string in all upper case letters.

trim() method removes any white spaces from the beginning and end of the string