01/10/2014

JavaScript Strings

A JavaScript string simply stores a series of characters like "John Elwin". A string can be any text inside quotes. You can use single or double quotes:
Example:
<body> <p id="demo"></p> <script> var carName1 = "Volvo XC60"; var carName2 = 'Volvo XC60'; document.getElementById("demo").innerHTML = carName1 + " " + carName2; </script> </body>
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example:
<body> <p id="demo"></p> <script> var answer1 = "It's alright"; var answer2 = "He is called 'John'"; var answer3 = 'He is called "John"'; document.getElementById("demo").innerHTML = answer1 + "<br>" + answer2 + "<br>" + answer3; </script> </body>
Or you can put quotes inside a string by using the \ escape character:
Example:
<body> <p id="demo"></p> <script> var answer1 = 'It\'s alright'; var answer2 = "He is called \"John\""; document.getElementById("demo").innerHTML = answer1 + " " + answer2; </script> </body>
String Length
The length of a string is found in the built in propertylength:
Example:
<body> <p id="demo"></p> <script> var txt= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; document.getElementById("demo").innerHTML = txt.length; </script> </body>
Special Characters
In JavaScript, strings are written as characters inside single or double quotes. Because of this, JavaScript will misunderstand this string:
"We are the so-called "Vikings" from the north"
The string will be chopped to "We are the so-called"
To solve this problem, you can place a backslash (\) before the double quotes in "Vikings": "We are the so-called \"Vikings\" from the north." The backslash is an escape character. Escape characters turns special characters into string characters: The escape character (\) can be used to insert a postrophes, new lines, quotes, and other special characters into a string. The table below lists other special characters that can be added to a text string with the backslash sign:
Code Table
Inputs Output
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
String Properties
Property Table
Property Description
constructor Returns the function that created the String object's prototype
length Returns the length of a string
prototype Allows you to add properties and methods to an object