Tuesday, July 8, 2014

06 - Strings

In JavaScript, characters are also strings with length 1, as demonstrated below:

var character = 'a';
var string = "abcdefg";

console.log(typeof(character)); // string
console.log(typeof(string)); // string

The code above also shows that a string can be inside both single and double quotes. Additionally, strings inside single quotes can have double quotes, and strings inside double quotes can have single quotes vice versa, as the strings str1 and str2 in the following piece of code. If you would like to use double quotes in a string surrounded by double quotes, an escape character "\" should be inserted before the double quotes in the string. Strings with single quotes are similar. Please take the strings str3 and str4 in the code below as examples:

var str1 = "I can't wait to learn JavaScript.";
var str2 = 'He said: "JavaScript is so good".';

console.log(str1); // I can't wait to learn JavaScript.
console.log(str2); // He said: "JavaScript is so good".

var str3 = 'I can\'t wait to learn JavaScript.';
var str4 = "He said: \"JavaScript is so good\".";

console.log(str1 == str3); // true
console.log(str2 == str4); // true

Strings can be split into multiple lines, when a ending character "\" at the each line, as show below:

var str = "<div> \
Learning JavaScript \

console.log(str); // <div> Learning JavaScript </div>

Strings in JavaScript are immutable. We could get a character from a string based on its index, but can modify it:

var str = "hello";
console.log(str[1]); // e

str[1] = 'a';
console.log(str[1]); // e

The character with index 1 in the string "hello" is "e". If we try to modify it to "a", the string keeps unchanged.

The type String has many methods to modify strings. The modified contents is accessible in the returned values, but the original strings are not modified, as demonstrated in the following piece of code:

var str1 = "hello";
var str2 = str1.replace("h", "H");

console.log(str1); // hello
console.log(str2); // Hello

The original value of the string str1 is "hello". When we try to replace the "h" with "H" in the string, str1 keeps unchanged, and the modified contents "Hello" is in the returned value which is referenced by str2.

No comments :

Post a Comment