JavaScript String

Programming languages without string data type is however not possible. String data type can store any type of data by simply converting it into the string, for e.g: we can convert the integer number into string like 12 to “12”, but we can not able to convert the string to int like “ABC” to ???. it simply throws the error.

May be most of the programming languages in the world store the string in the double quote(“”) only and store the characters in the single quote(”) so there is difference between the double quote(“”) and single quote(”) in many programming languages but in JavaScript double quote(“”) and single quote(”) both are the same so we can simply store the string in both the double quote(“”) and single quote(”) and in JavaScript there is no characters and string like concepts.

So we can create the string in JavaScript in both way using the double quote and single quote.

var str1 = "JavaScript Hive";
var str2 = 'I am learning the JavaScript';
var str3 = new String("String 3");

One main feature of the JavaSctipt String is that it store it self in the Unicode format.

Special Characters

Characters Description
\n New line
\b Backspace
\t Tab
\r Carriage return
\\ Backslash
\’ Single Quote
\” Double Quote

Escaping special characters from the string

Like any other programming languages we can also escape the special characters from the string. Many time when we are using the string we have to escape the special characters and we are also stuck there.

In JavaScript we can use the backslash(‘\’) to escape the special character, we have to simply add the backslash before the special character.

var str1 = 'I\'m awesome';
alert(str1);
var str2 = "You are \"awesome\"";
alert(str2);

String’s Methods & Properties

Length

JavaScript string’s length property is return the count of the characters into the sting.

var str1 = "JavaScript Hive";
alert(str1.length);

toLowerCase() & toUperCase()

JavaScript also provides the two methods for the changing the string case. This method will change the case of whole string.

var str1 = "JavaScript Hive";
alert(str1.toLowerCase());
alert(str1.toUpperCase());

charAt()

By using the charAt() method of the string we can get the character from the string using it’s index. charAt() method simply returns the single character from string from the specific index.

Keep in mind if some says the index than it always start with ZERO. charAt() function accept the index if you want the first character of the string than you have to passed the zero as argument.

var str1 = "JavaScript Hive";
alert(str1.charAt(0));
alert(str1.charAt(4));

If you pass the index that not present in the string or simply say that you pass the index out of bound the charAt() method does not return anything.

var str1 = "JavaScript Hive";
alert(str1.charAt(15));

Happy Coding!!!

🙂