JavaScript (string of charecter). (char).
UTF-16, .
().
:
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;
. ${}:
function sum(a, b) {
return a + b;
}
alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.
:
let guestList = `Guests:
* John
* Pete
* Mary
`;
alert(guestList); //
. :
let guestList = "Guests: // Error: Unexpected token ILLEGAL
* John";
. .
Backticks also allow us to specify a template function before the first backtick. The syntax is: func`string`. The function func is called automatically, receives the string and embedded expressions and can process them. This is called tagged templates. This feature makes it easier to implement custom templating, but is rarely used in practice. You can read more about it in the manual.
\n :
let guestList = "Guests:\n * John\n * Pete\n * Mary";
alert(guestList); //
:
let str1 = "Hello\nWorld"; // " "
//
let str2 = `Hello
World`;
alert(str1 == str2); // true
.
:
\n |
(Line Feed). |
\r |
(Carriage Return) . \r\n . |
'\ , "\ |
. |
\\ |
|
\t |
Tab |
\b, \f, \v |
(backspace) (Form Feed) (Vertical Tab) . |
\xXX |
XX : ' \x7A' 'z'. |
\uXXXX |
XXXX UTF-16 \u00A9 . 6 . |
\u{XXXXXXX} |
(1 6 ) UTF-32 . 4 . . |
| Character | Description |
|---|---|
\n |
New line |
\r |
Carriage return: not used alone. Windows text files use a combination of two characters \r\n to represent a line break. |
\', \" |
Quotes |
\\ |
Backslash |
\t |
Tab |
\b, \f, \v |
Backspace, Form Feed, Vertical Tab kept for compatibility, not used nowadays. |
\xXX |
Unicode character with the given hexadecimal Unicode XX, e.g. '\x7A' is the same as 'z'. |
\uXXXX |
A Unicode symbol with the hex code XXXX in UTF-16 encoding, for instance \u00A9 is a Unicode for the copyright symbol . It must be exactly 4 hex digits. |
\u{XXXXXXX} (1 to 6 hex characters) |
A Unicode symbol with the given UTF-32 encoding. Some rare characters are encoded with two Unicode symbols, taking 4 bytes. This way we can insert long codes. |
Examples with Unicode:
alert( "\u00A9" ); //
alert( "\u{20331}" ); // , a rare Chinese hieroglyph (long Unicode)
alert( "\u{1F60D}" ); // , a smiling face symbol (another long Unicode)
// ( ( alert( \u{20331} ); //
// ( ( alert( \u{1F60D} ); //
`\`. " " (escape character). : :
```js run
alert( 'I\'m the Walrus!' ); // I'm the Walrus!
\' . \ JavaScript. \. alert .
Of course, only the quotes that are the same as the enclosing ones need to be escaped. So, as a more elegant solution, we could switch to double quotes or backticks instead:
alert( `I'm the Walrus!` ); // I'm the Walrus!
\\:
alert( `The backslash: \\` ); // The backslash: \
length :
alert( `My\n`.length ); // 3
n\ 3.
length str.length() str.length . . str.length .
pos [pos] str.charAt(pos). :
let str = `Hello`;
// the first character
alert( str[0] ); // H
alert( str.charAt(0) ); // H
// the last character
alert( str[str.length - 1] ); // o
charAt . [] undefined charAt :
let str = `Hello`;
alert( str[1000] ); // undefined
alert( str.charAt(1000) ); // '' ( )
for..of:
for (let char of "Hello") {
alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc)
}
JavaScript . :
let str = 'Hi';
str[0] = 'h'; //
alert( str[0] ); //
str . :
let str = 'Hi';
str = 'h' + str[1]; //
alert( str ); // hi
.
alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface
:
alert( 'Interface'[0].toLowerCase() ); // 'i'
.
str.indexOf
substr str pos -1 . :
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 start searching from a given position.
For instance, the first occurrence of "id" is at position 1. To look for the next occurrence, lets start the search from position 2:
let str = 'Widget with id';
alert( str.indexOf('id', 2) ) // 12
indexOf . :
let str = 'As sly as a fox, as strong as an ox';
let target = 'as'; // let's look for it
let pos = 0;
while (true) {
let foundPos = str.indexOf(target, pos);
if (foundPos == -1) break;
alert( `Found at ${foundPos}` );
pos = foundPos + 1; // continue the search from the next position
}
:
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 );
}
str.lastIndexOf(substr, position) indexOf if. if :
let str = "Widget with id";
if (str.indexOf("Widget")) {
alert("We found it"); // !
}
str.indexOf("Widget") 0 ( ) if 0 false. - 1 :
let str = "Widget with id";
if (str.indexOf("Widget") != -1) {
alert("We found it"); // works now!
}
The bitwise NOT trick
One of the old tricks used here is the bitwise NOT ~ operator. It converts the number to a 32-bit integer (removes the decimal part if exists) and then reverses all bits in its binary representation.
In practice, that means a simple thing: for 32-bit integers ~n equals -(n+1).
~ . 32- ( ) . : 32- ~n -(n+1). :
alert( ~2 ); // -3, the same as -(2+1)
alert( ~1 ); // -2, the same as -(1+1)
alert( ~0 ); // -1, the same as -(0+1)
alert( ~-1 ); // 0, the same as -(-1+1)
~n n == -1 ( n ). if ( ~str.indexOf("...") ) indexOf -1. true .
indexOf:
let str = "Widget";
if (~str.indexOf("Widget")) {
alert( 'Found it!' ); // works
}
.
if (~str.indexOf(...)) .
To be precise though, as big numbers are truncated to 32 bits by ~ operator, there exist other numbers that give 0, the smallest is ~4294967295=0. That makes such check correct only if a string is not that long.
JavaScript .includes ( ).
includes, startsWith, endsWith
str.includes(substr, pos) true false str substr. :
alert( "Widget with id".includes("Widget") ); // true
alert( "Hello".includes("Bye") ); // false
str.includes :
alert( "Widget".includes("id") ); // true
alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id"
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.
str.slice(start [, end])
start end ( end).
:
```js run
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
```
`slice` `start` :
```js run
let str = "st*!*ringify*/!*";
alert( str.slice(2) ); // 'ringify', from the 2nd position till the end
```
`start` `end` :
```js run
let str = "strin*!*gif*/!*y";
// start at the 4th position from the right, end at the 1st from the right
alert( str.slice(-4, -1) ); // 'gif'
```
str.substring(start [, end])
start end.
`. `slice` `start` `end`.
:
```js run
let str = "stringify";
// substring
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"
// slice
alert( str.slice(2, 6) ); // "ring" ( )
alert( str.slice(6, 2) ); // "" ( )
```
`slice` `0` .
str.substr(start [, length])
start length
:
```js run
let str = "stringify";
// 4 2
alert( str.substr(2, 4) ); // ring
```
:
```js run
let str = "strin*!*gi*/!*fy";
alert( str.substr(-4, 2) ); //
```
:
slice(start, end) |
start end ( end) |
|
substring(start, end) |
start end |
0 |
substr(start, length) |
length start |
start |
. substr : JavaScript Annex B .
slice . slice .
, strings are compared character-by-character in alphabetical order.
.
1- :
```js run
alert( 'a' > 'Z' ); // true
```
2- :
```js run
alert( 'sterreich' > 'Zealand' ); // true
```
Zealand sterreich . JavaScript.
UTF-16. : . .
str.codePointAt(pos)
pos:
```js run
//
alert( "z".codePointAt(0) ); // 122
alert( "Z".codePointAt(0) ); // 90
```
String.fromCodePoint(code)
code:
```js run
alert( String.fromCodePoint(90) ); // Z
```
We can also add Unicode characters by their codes using `\u` followed by the hex code:
```js run
// 90 5a .
alert( '\u005a' ); // Z
```
65..220 ( ) :
let str = '';
for (let i = 65; i <= 220; i++) {
str += String.fromCodePoint(i);
}
alert( str );
// ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
//
.
a > Z. . . a 97 Z 90.
- .
-
.az.
Correct comparisons
str.localeCompare(str2) str str2 :
-
strstr2. -
strstr2. -
0.
:
alert( 'sterreich'.localeCompare('Zealand') ); // -1
mdn:js/String/localeCompare
MDN ( ) "a" "a" .
. .
(Surrogate pairs)
(code) 2-. 2-.
2- 65536 (symbol) (symbol) 2- (Surrogate pairs).
2:
// X
alert( ''.length ); // 2
//
alert( ''.length ); // 2
//
alert( ''.length ); // 2
JavaScript . length 2.
String.fromCodePoint str.codePointAt . . String.fromCharCode str.charCodeAt . fromCodePoint codePointAt .
(symbol) :
alert( ''[0] ); // .
alert( ''[1] ); //
. alert .
: 0xd800..0xdbff . 0xdc00..0xdfff. .
charCodeAt
:
//
alert( ''.charCodeAt(0).toString(16) ); // d835, between 0xd800 and 0xdbff
alert( ''.charCodeAt(1).toString(16) ); // dcb3, between 0xdc00 and 0xdfff
Iterables. .
/. a : . UTF-16. .
To support arbitrary compositions, UTF-16 allows us to use several Unicode characters: the base character followed by one or many mark characters that decorate it.
alert( 'S\u0307' ); // S
. ( \u0323) S S:
alert( 'S\u0307\u0323' ); // S
This provides great flexibility, but also an interesting problem: two characters may visually look the same, but be represented with different Unicode compositions.
For instance:
// S + +
let s1 = 'S\u0307\u0323'; // S
// S + +
let s2 = 'S\u0323\u0307'; // S,
alert( `s1: ${s1}, s2: ${s2}` );
alert( s1 == s2 ); //
To solve this, there exists a Unicode normalization algorithm that brings each string to the single normal form.
alert( "S\u0307\u0323".normalize() == "S\u0323\u0307".normalize() ); // true
normalize() 3 : \u1e68 ( S ).
alert( "S\u0307\u0323".normalize().length ); // 1
alert( "S\u0307\u0323".normalize() == "\u1e68" ); // true
. UTF-16 .
- There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions
${}. - Strings in JavaScript are encoded using UTF-16.
- We can use special characters like
\nand insert letters by their Unicode using\u.... - To get a character, use:
[]. - To get a substring, use:
sliceorsubstring. - To lowercase/uppercase a string, use:
toLowerCase/toUpperCase. - To look for a substring, use:
indexOf, orincludes/startsWith/endsWithfor simple checks. - To compare strings according to the language, use:
localeCompare, otherwise they are compared by character codes.
:
str.trim()() .str.repeat(n)n.- manual.
/ (regular expressions). Regular expressions.
<code><pre>10 (plnkr, JSBin, codepen)