In this post, I will be explaining how to use work with strings using JavaScript.
What Are Strings?
Strings are used for storing and manipulating text. You can declare them by wrapping quotes around zero or more characters, using either or single quotes or double quotes.
Escaping Special Characters
Strings must be written in quotes, otherwise, your machine cannot possibly understand them. However, this can cause some odd problems at times. For example, what if you want to write a quote in a string? To create that, you need to do something called escaping special characters.
Quotes aren't the only thing you will need to escape. Below are three examples of common things you will need to escape to display them as strings.
Javascript Code
var x = "This disaster was the worst \"present\" we ever got";
Javascript Code
var x = 'That\'s my dog, Samuel.';
Javascript Code
var x = "This character \\ is called a backslash.";
In the table below, we have some less commonly used values that will need to escape to display properly in a string.
Code | Result |
\b | Backspace |
\f | Form Feed |
\n | New Line |
\r | Carriage Return |
\t | Horizontal Tabulator |
\v | Vertical Tabulator |
Strings can be objects So normally strings are primitive values. One odd fact is that you can also create string objects using the String() function. However, there isn't any point in this and it slows down the execution speed. Hence this is just an odd tidbit.
Javascript Code
var x = "James";
var y = new String("James");
// typeof x will return string
// typeof y will return object
Comparison
JavaScript Code
var x = "Orange";
var y = new String("Orange");
// (x == y) is true because x and y are the same value.
When you compare an object string with a primitive string using “==“
, you are comparing value.
So the above example will return true.
JavaScript Code
var x = "Orange";
var y = new String("Orange");
// (x === y) is false because while x and y have the same value, they are different objects
However, when you compare an object string with a primitive string using “===”
, you are comparing both value and type.
So the above example will return false.