There are special character you can include inside a string, these special character are called Escape Sequence
. These character cannot be used directly inside the string. Here are few special character -
\n
: This means a new line.\b
: This represents a backspace.\t
: This represents a Tab inside the string.\'
: This prints a single quote.\"
: This prints a double quote.\\
: This prints a blackslash inside the string.As you can see each special symbol starts with a blackslash.
Remember that if you use double quote for string, you can print single quote inside the string directly, you don't need to escape the character with backslash. Also If you use single quote for string, you can print double quote directly. For example -
let hi = "My Pet's Home"; let hi = 'He said, "How are you?"';
If you use backticks for sting, you can print single or double quote directly.
let hi = `My Pet's Home`; let hi = `He said, "How are you?"`;
If you want to print single quote within the string which is enclosed with single quote, you need to escape it with backslash. Similarly, if you want to print double quote which is enclosed with double quote, you need to escape it with backslash.
let hi = 'My Pet\'s Home'; let hi = "He said, \"How are you?\"";
If you need to print backslash within the string use double backslash -
alert( `The backslash: \\` ); // The backslash: \
Here are few example of escape sequence -
let guestList = "Guests:\n * John\n * Pete\n * Mary"; alert(guestList); // a multiline list of guests alert( "Hello\nWorld" ); // two lines using a "newline symbol"
You can use hexa code to represent other special symbol. Hexa code starts with \u
followed by four Hexa digits.
\uNNNN
It must be exactly 4 hex digits. For example -
alert( "\u00A9" ); // ©
Some rare characters are encoded with two unicode symbols, taking up to 4 bytes. This long unicode requires braces around it.
\u{NNNNNNNN}
For example -
alert( "\u{20331}" ); // 佫, a rare chinese hieroglyph (long unicode) alert( "\u{1F60D}" ); // 😍, a smiling face symbol (another long unicode)
To get the number of character that a string contains use the property length
-
alert( `My\n`.length ); // 3 alert("Santanu".length); // 7
Note that \n
is a single “special” character, so the length is indeed 3
.
To get a character at position pos, use square brackets [pos] or call the method str.charAt(pos). The first character starts from the zero position:
let str = `Hello`; // the first character alert( str[0] ); // H alert( str.charAt(0) ); // H // the last character alert( str[str.length - 1] ); // o
The square brackets are a modern way of getting a character, while charAt exists mostly for historical reasons. The only difference between them is that if no character is found, []
returns undefined
, and charAt
returns an empty string:
let str = `Hello`; alert( str[1000] ); // undefined alert( str.charAt(1000) ); // '' (an empty string)
We can also iterate over characters using for..of:
for (let char of "Hello") { alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc) }
Strings can’t be changed in JavaScript. It is impossible to change a character. Let’s try it to show that it doesn’t work:
let str = 'Hi'; str[0] = 'h'; // error alert( str[0] ); // doesn't work
The usual workaround is to create a whole new string and assign it to str
instead of the old one.
let str = 'Hi'; str = 'h' + str[1]; // replace the string alert( str ); // hi
Methods toLowerCase()
and toUpperCase()
change the case:
alert( 'Interface'.toUpperCase() ); // INTERFACE alert( 'Interface'.toLowerCase() ); // interface
Or, if we want a single character lowercased:
alert( 'Interface'[0].toLowerCase() ); // 'i'
There are multiple ways to look for a substring within a string.
It looks for the substr
in str
, starting from the given position pos
, and returns the position where the match was found or -1
if nothing can be found.
let str = 'Widget with id'; alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)
The optional second parameter allows us to search starting from the given position.
For instance, the first occurrence of "id" is at position 1. To look for the next occurrence, let’s start the search from position 2:
let str = 'Widget with id'; alert( str.indexOf('id', 2) ) // 12
If you want to search for all the occurance of the substr, then you can run the method within a loop with updated pos. Here is the code -
let str = "As sly as a fox, as strong as an ox"; let target = "as"; let pos = -1; while ((pos = str.indexOf(target, pos + 1)) != -1) { alert( pos ); }
There is a slight inconvenience with indexOf in the if test. We can’t put it in the if like this:
let str = "Widget with id"; if (str.indexOf("Widget")) { alert("We found it"); // doesn't work! }
The alert in the example above doesn’t show because str.indexOf("Widget")
returns 0
(meaning that it found the match at the starting position). Right, but if considers 0
to be false
.
So, we should actually check for -1
, like this:
let str = "Widget with id"; if (str.indexOf("Widget") != -1) { alert("We found it"); // works now! }
The more modern method str.includes(substr, pos)
returns true
/false
depending on whether str
contains substr
within.
It’s the right choice if we need to test for the match, but don’t need its position:
alert( "Widget with id".includes("Widget") ); // true alert( "Hello".includes("Bye") ); // false
The optional second argument of str.includes
is the position to start searching from:
alert( "Midget".includes("id") ); // true alert( "Midget".includes("id", 3) ); // false, from position 3 there is no "id"
The methods str.startsWith
and str.endsWith
do exactly what they say:
alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid" alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get"
There are 3 methods in JavaScript to get a substring: substring
, substr
and slice
.
Returns the part of the string from start
to end
(but not including).
let str = "stringify"; alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5) alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0
If there is no second argument, then slice goes till the end of the string:
let str = "stringify"; alert( str.slice(2) ); // ringify, from the 2nd position till the end
Negative values for start/end are also possible. They mean the position is counted from the string end:
let str = "stringify"; // start at the 4th position from the right, end at the 1st from the right alert( str.slice(-4, -1) ); // gif
Note that, the counting starts with -1
from the right side.
Returns the part of the string between start
and end
. This is almost the same as slice, but it allows start
to be greater than end
.
let str = "stringify"; // these are same for substring alert( str.substring(2, 6) ); // "ring" alert( str.substring(6, 2) ); // "ring" // ...but not for slice: alert( str.slice(2, 6) ); // "ring" (the same) alert( str.slice(6, 2) ); // "" (an empty string)
Between these two arguments, whichever is small is considered as the starting index.
Negative arguments are (unlike slice) not supported, they are treated as 0
.
Returns the part of the string from start
, with the given length
. In contrast with the previous methods, this one allows us to specify the length instead of the ending position:
let str = "stringify"; alert( str.substr(2, 4) ); // ring, from the 2nd position get 4 characters
The first argument may be negative, to count from the end
:
let str = "stringify"; alert( str.substr(-4, 2) ); // gi, from the 4th position get 2 characters
Note that, the second argument, length
cannot be negative.
All strings are encoded using UTF-16
. That is: each character has a corresponding numeric code. There are special methods that allow to get the character for the code and back.
Returns the code for the character at position pos
:
// different case letters have different codes alert( "z".codePointAt(0) ); // 122 alert( "Z".codePointAt(0) ); // 90
Creates a character by its numeric code
alert( String.fromCodePoint(90) ); // Z