Notes Javascript - Text Formatting
Text Formatting
JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects.
String Literals
var s = 'foo'; // NOTE SINGLE QUOTES var s = "bar"; // NOTE DOUBLE QUOTES
Extended Characters
The following are methods to represent characters beyond what it available on a standard US-Keyboard.
Type | Syntax |
---|---|
Hexidecimal | \x## |
Unicode | \u#### |
String.fromCharCode()
The String.fromCharCode() static method returns a string created from the specified sequence of UTF-16 code units.
num1, ...,numN | A sequence of numbers that are UTF-16 code units. The range is between 0 and 65535 (0xFFFF). Numbers greater than 0xFFFF are truncated. No validity checks are performed. |
---|
String.fromCharCode(num1) String.fromCharCode(num1, num2) String.fromCharCode(num1, num2, /* ..., */ numN)
function runScript1() { let resultDiv = document.getElementById("results1"); let resultStr = ""; let s1 = "\xA9"; // HEX: COPYWRITE CHARACTER let s2 = "\u00A9"; // UNICODE: COPYWRITE CHARACTER let s3 = String.fromCharCode(65,66,67); // RETURNS ABC let s4 = String.fromCharCode(0x2014); // RETURNS Em Dash let s5 = String.fromCharCode(0x65); // RETURNS e let s6 = String.fromCharCode(65); // RETURNS A resultStr = "s1: "+ s1; resultStr += "</br>s2: "+ s2; resultStr += "</br>s3: "+ s3; resultStr += "</br>s4: "+ s4; resultStr += "</br>s5: "+ s5; resultStr += "</br>s6: "+ s6; resultDiv.innerHTML = resultStr; }
Run ScriptCharacter Sets
Decimal | Octal | Hex | Bin | Symbol | HTML | Name | Description |
---|---|---|---|---|---|---|---|
32 | 040 | 20 | 00100000 | SP |   | Space | |
33 | 041 | 21 | 00100001 | ! | ! | ! | Exclamation mark |
34 | 042 | 22 | 00100010 | " | " | " | Double quotes (or speech marks) |
35 | 043 | 23 | 00100011 | # | # | # | Number sign |
36 | 044 | 24 | 00100100 | $ | $ | $ | Dollar |
37 | 045 | 25 | 00100101 | % | % | % | Per cent sign |
38 | 046 | 26 | 00100110 | & | & | & | Ampersand |
39 | 047 | 27 | 00100111 | ' | ' | ' | Single quote |
40 | 050 | 28 | 00101000 | ( | ( | &lparen; | Open parenthesis (or open bracket) |
41 | 051 | 29 | 00101001 | ) | ) | &rparen; | Close parenthesis (or close bracket) |
42 | 052 | 2A | 00101010 | * | * | * | Asterisk |
43 | 053 | 2B | 00101011 | + | + | + | Plus |
44 | 054 | 2C | 00101100 | , | , | , | Comma |
45 | 055 | 2D | 00101101 | - | - | Hyphen-minus | |
46 | 056 | 2E | 00101110 | . | . | . | Period, dot or full stop |
47 | 057 | 2F | 00101111 | / | / | / | Slash or divide |
48 | 060 | 30 | 00110000 | 0 | 0 | Zero | |
49 | 061 | 31 | 00110001 | 1 | 1 | One | |
50 | 062 | 32 | 00110010 | 2 | 2 | Two | |
51 | 063 | 33 | 00110011 | 3 | 3 | Three | |
52 | 064 | 34 | 00110100 | 4 | 4 | Four | |
53 | 065 | 35 | 00110101 | 5 | 5 | Five | |
54 | 066 | 36 | 00110110 | 6 | 6 | Six | |
55 | 067 | 37 | 00110111 | 7 | 7 | Seven | |
56 | 070 | 38 | 00111000 | 8 | 8 | Eight | |
57 | 071 | 39 | 00111001 | 9 | 9 | Nine | |
58 | 072 | 3A | 00111010 | : | : | : | Colon |
59 | 073 | 3B | 00111011 | ; | ; | ; | Semicolon |
60 | 074 | 3C | 00111100 | < | < | < | Less than (or open angled bracket) |
61 | 075 | 3D | 00111101 | = | = | = | Equals |
62 | 076 | 3E | 00111110 | > | > | > | Greater than (or close angled bracket) |
63 | 077 | 3F | 00111111 | ? | ? | ? | Question mark |
64 | 100 | 40 | 01000000 | @ | @ | @ | At sign |
65 | 101 | 41 | 01000001 | A | A | Uppercase A | |
66 | 102 | 42 | 01000010 | B | B | Uppercase B | |
67 | 103 | 43 | 01000011 | C | C | Uppercase C | |
68 | 104 | 44 | 01000100 | D | D | Uppercase D | |
69 | 105 | 45 | 01000101 | E | E | Uppercase E | |
70 | 106 | 46 | 01000110 | F | F | Uppercase F | |
71 | 107 | 47 | 01000111 | G | G | Uppercase G | |
72 | 110 | 48 | 01001000 | H | H | Uppercase H | |
73 | 111 | 49 | 01001001 | I | I | Uppercase I | |
74 | 112 | 4A | 01001010 | J | J | Uppercase J | |
75 | 113 | 4B | 01001011 | K | K | Uppercase K | |
76 | 114 | 4C | 01001100 | L | L | Uppercase L | |
77 | 115 | 4D | 01001101 | M | M | Uppercase M | |
78 | 116 | 4E | 01001110 | N | N | Uppercase N | |
79 | 117 | 4F | 01001111 | O | O | Uppercase O | |
80 | 120 | 50 | 01010000 | P | P | Uppercase P | |
81 | 121 | 51 | 01010001 | Q | Q | Uppercase Q | |
82 | 122 | 52 | 01010010 | R | R | Uppercase R | |
83 | 123 | 53 | 01010011 | S | S | Uppercase S | |
84 | 124 | 54 | 01010100 | T | T | Uppercase T | |
85 | 125 | 55 | 01010101 | U | U | Uppercase U | |
86 | 126 | 56 | 01010110 | V | V | Uppercase V | |
87 | 127 | 57 | 01010111 | W | W | Uppercase W | |
88 | 130 | 58 | 01011000 | X | X | Uppercase X | |
89 | 131 | 59 | 01011001 | Y | Y | Uppercase Y | |
90 | 132 | 5A | 01011010 | Z | Z | Uppercase Z | |
91 | 133 | 5B | 01011011 | [ | [ | [ | Opening bracket |
92 | 134 | 5C | 01011100 | \ | \ | \ | Backslash |
93 | 135 | 5D | 01011101 | ] | ] | ] | Closing bracket |
94 | 136 | 5E | 01011110 | ^ | ^ | ^ | Caret - circumflex |
95 | 137 | 5F | 01011111 | _ | _ | _ | Underscore |
96 | 140 | 60 | 01100000 | ` | ` | ` | Grave accent |
97 | 141 | 61 | 01100001 | a | a | Lowercase a | |
98 | 142 | 62 | 01100010 | b | b | Lowercase b | |
99 | 143 | 63 | 01100011 | c | c | Lowercase c | |
100 | 144 | 64 | 01100100 | d | d | Lowercase d | |
101 | 145 | 65 | 01100101 | e | e | Lowercase e | |
102 | 146 | 66 | 01100110 | f | f | Lowercase f | |
103 | 147 | 67 | 01100111 | g | g | Lowercase g | |
104 | 150 | 68 | 01101000 | h | h | Lowercase h | |
105 | 151 | 69 | 01101001 | i | i | Lowercase i | |
106 | 152 | 6A | 01101010 | j | j | Lowercase j | |
107 | 153 | 6B | 01101011 | k | k | Lowercase k | |
108 | 154 | 6C | 01101100 | l | l | Lowercase l | |
109 | 155 | 6D | 01101101 | m | m | Lowercase m | |
110 | 156 | 6E | 01101110 | n | n | Lowercase n | |
111 | 157 | 6F | 01101111 | o | o | Lowercase o | |
112 | 160 | 70 | 01110000 | p | p | Lowercase p | |
113 | 161 | 71 | 01110001 | q | q | Lowercase q | |
114 | 162 | 72 | 01110010 | r | r | Lowercase r | |
115 | 163 | 73 | 01110011 | s | s | Lowercase s | |
116 | 164 | 74 | 01110100 | t | t | Lowercase t | |
117 | 165 | 75 | 01110101 | u | u | Lowercase u | |
118 | 166 | 76 | 01110110 | v | v | Lowercase v | |
119 | 167 | 77 | 01110111 | w | w | Lowercase w | |
120 | 170 | 78 | 01111000 | x | x | Lowercase x | |
121 | 171 | 79 | 01111001 | y | y | Lowercase y | |
122 | 172 | 7A | 01111010 | z | z | Lowercase z | |
123 | 173 | 7B | 01111011 | { | { | { | Opening brace |
124 | 174 | 7C | 01111100 | | | | | | | Vertical bar |
125 | 175 | 7D | 01111101 | } | } | } | Closing brace |
126 | 176 | 7E | 01111110 | ~ | ~ | ˜ | Equivalency sign - tilde |
127 | 177 | 7F | 01111111 | DEL |  | Delete |
Decimal | Octal | Hex | Bin | Symbol | HTML | Name | Description |
---|---|---|---|---|---|---|---|
128 | 200 | 80 | 10000000 | € | € | € | Euro sign |
129 | 201 | 81 | 10000001 | Unused | |||
130 | 202 | 82 | 10000010 | ‚ | ‚ | ‚ | Single low-9 quotation mark |
131 | 203 | 83 | 10000011 | ƒ | ƒ | ƒ | Latin small letter f with hook |
132 | 204 | 84 | 10000100 | „ | „ | „ | Double low-9 quotation mark |
133 | 205 | 85 | 10000101 | … | … | … | Horizontal ellipsis |
134 | 206 | 86 | 10000110 | † | † | † | Dagger |
135 | 207 | 87 | 10000111 | ‡ | ‡ | ‡ | Double dagger |
136 | 210 | 88 | 10001000 | ˆ | ˆ | ˆ | Modifier letter circumflex accent |
137 | 211 | 89 | 10001001 | ‰ | ‰ | ‰ | Per mille sign |
138 | 212 | 8A | 10001010 | Š | Š | Š | Latin capital letter S with caron |
139 | 213 | 8B | 10001011 | ‹ | ‹ | ‹ | Single left-pointing angle quotation |
140 | 214 | 8C | 10001100 | Œ | Œ | Œ | Latin capital ligature OE |
141 | 215 | 8D | 10001101 | Unused | |||
142 | 216 | 8E | 10001110 | Ž | Ž | Ž | Latin capital letter Z with caron |
143 | 217 | 8F | 10001111 | Unused | |||
144 | 220 | 90 | 10010000 | Unused | |||
145 | 221 | 91 | 10010001 | ‘ | ‘ | ‘ | Left single quotation mark |
146 | 222 | 92 | 10010010 | ’ | ’ | ’ | Right single quotation mark |
147 | 223 | 93 | 10010011 | “ | “ | “ | Left double quotation mark |
148 | 224 | 94 | 10010100 | ” | ” | ” | Right double quotation mark |
149 | 225 | 95 | 10010101 | • | • | • | Bullet |
150 | 226 | 96 | 10010110 | – | – | – | En dash |
151 | 227 | 97 | 10010111 | — | — | — | Em dash |
152 | 230 | 98 | 10011000 | ˜ | ˜ | ˜ | Small tilde |
153 | 231 | 99 | 10011001 | ™ | ™ | ™ | Trade mark sign |
154 | 232 | 9A | 10011010 | š | š | š | Latin small letter S with caron |
155 | 233 | 9B | 10011011 | › | › | › | Single right-pointing angle quotation mark |
156 | 234 | 9C | 10011100 | œ | œ | œ | Latin small ligature oe |
157 | 235 | 9D | 10011101 | Unused | |||
158 | 236 | 9E | 10011110 | ž | ž | ž | Latin small letter z with caron |
159 | 237 | 9F | 10011111 | Ÿ | Ÿ | Ÿ | Latin capital letter Y with diaeresis |
160 | 240 | A0 | 10100000 | NBSP |   | | Non-breaking space |
161 | 241 | A1 | 10100001 | ¡ | ¡ | ¡ | Inverted exclamation mark |
162 | 242 | A2 | 10100010 | ¢ | ¢ | ¢ | Cent sign |
163 | 243 | A3 | 10100011 | £ | £ | £ | Pound sign |
164 | 244 | A4 | 10100100 | ¤ | ¤ | ¤ | Currency sign |
165 | 245 | A5 | 10100101 | ¥ | ¥ | ¥ | Yen sign |
166 | 246 | A6 | 10100110 | ¦ | ¦ | ¦ | Pipe, broken vertical bar |
167 | 247 | A7 | 10100111 | § | § | § | Section sign |
168 | 250 | A8 | 10101000 | ¨ | ¨ | ¨ | Spacing diaeresis - umlaut |
169 | 251 | A9 | 10101001 | © | © | © | Copyright sign |
170 | 252 | AA | 10101010 | ª | ª | ª | Feminine ordinal indicator |
171 | 253 | AB | 10101011 | « | « | « | Left double angle quotes |
172 | 254 | AC | 10101100 | ¬ | ¬ | ¬ | Negation |
173 | 255 | AD | 10101101 | SHY | ­ | ­ | Soft hyphen |
174 | 256 | AE | 10101110 | ® | ® | ® | Registered trade mark sign |
175 | 257 | AF | 10101111 | ¯ | ¯ | ¯ | Spacing macron - overline |
176 | 260 | B0 | 10110000 | ° | ° | ° | Degree sign |
177 | 261 | B1 | 10110001 | ± | ± | ± | Plus-or-minus sign |
178 | 262 | B2 | 10110010 | ² | ² | ² | Superscript two - squared |
179 | 263 | B3 | 10110011 | ³ | ³ | ³ | Superscript three - cubed |
180 | 264 | B4 | 10110100 | ´ | ´ | ´ | Acute accent - spacing acute |
181 | 265 | B5 | 10110101 | µ | µ | µ | Micro sign |
182 | 266 | B6 | 10110110 | ¶ | ¶ | ¶ | Pilcrow sign - paragraph sign |
183 | 267 | B7 | 10110111 | · | · | · | Middle dot - Georgian comma |
184 | 270 | B8 | 10111000 | ¸ | ¸ | ¸ | Spacing cedilla |
185 | 271 | B9 | 10111001 | ¹ | ¹ | ¹ | Superscript one |
186 | 272 | BA | 10111010 | º | º | º | Masculine ordinal indicator |
187 | 273 | BB | 10111011 | » | » | » | Right double angle quotes |
188 | 274 | BC | 10111100 | ¼ | ¼ | ¼ | Fraction one quarter |
189 | 275 | BD | 10111101 | ½ | ½ | ½ | Fraction one half |
190 | 276 | BE | 10111110 | ¾ | ¾ | ¾ | Fraction three quarters |
191 | 277 | BF | 10111111 | ¿ | ¿ | ¿ | Inverted question mark |
192 | 300 | C0 | 11000000 | À | À | À | Latin capital letter A with grave |
193 | 301 | C1 | 11000001 | Á | Á | Á | Latin capital letter A with acute |
194 | 302 | C2 | 11000010 | Â | Â | Â | Latin capital letter A with circumflex |
195 | 303 | C3 | 11000011 | Ã | Ã | Ã | Latin capital letter A with tilde |
196 | 304 | C4 | 11000100 | Ä | Ä | Ä | Latin capital letter A with diaeresis |
197 | 305 | C5 | 11000101 | Å | Å | Å | Latin capital letter A with ring above |
198 | 306 | C6 | 11000110 | Æ | Æ | Æ | Latin capital letter AE |
199 | 307 | C7 | 11000111 | Ç | Ç | Ç | Latin capital letter C with cedilla |
200 | 310 | C8 | 11001000 | È | È | È | Latin capital letter E with grave |
201 | 311 | C9 | 11001001 | É | É | É | Latin capital letter E with acute |
202 | 312 | CA | 11001010 | Ê | Ê | Ê | Latin capital letter E with circumflex |
203 | 313 | CB | 11001011 | Ë | Ë | Ë | Latin capital letter E with diaeresis |
204 | 314 | CC | 11001100 | Ì | Ì | Ì | Latin capital letter I with grave |
205 | 315 | CD | 11001101 | Í | Í | Í | Latin capital letter I with acute |
206 | 316 | CE | 11001110 | Î | Î | Î | Latin capital letter I with circumflex |
207 | 317 | CF | 11001111 | Ï | Ï | Ï | Latin capital letter I with diaeresis |
208 | 320 | D0 | 11010000 | Ð | Ð | Ð | Latin capital letter ETH |
209 | 321 | D1 | 11010001 | Ñ | Ñ | Ñ | Latin capital letter N with tilde |
210 | 322 | D2 | 11010010 | Ò | Ò | Ò | Latin capital letter O with grave |
211 | 323 | D3 | 11010011 | Ó | Ó | Ó | Latin capital letter O with acute |
212 | 324 | D4 | 11010100 | Ô | Ô | Ô | Latin capital letter O with circumflex |
213 | 325 | D5 | 11010101 | Õ | Õ | Õ | Latin capital letter O with tilde |
214 | 326 | D6 | 11010110 | Ö | Ö | Ö | Latin capital letter O with diaeresis |
215 | 327 | D7 | 11010111 | × | × | × | Multiplication sign |
216 | 330 | D8 | 11011000 | Ø | Ø | Ø | Latin capital letter O with slash |
217 | 331 | D9 | 11011001 | Ù | Ù | Ù | Latin capital letter U with grave |
218 | 332 | DA | 11011010 | Ú | Ú | Ú | Latin capital letter U with acute |
219 | 333 | DB | 11011011 | Û | Û | Û | Latin capital letter U with circumflex |
220 | 334 | DC | 11011100 | Ü | Ü | Ü | Latin capital letter U with diaeresis |
221 | 335 | DD | 11011101 | Ý | Ý | Ý | Latin capital letter Y with acute |
222 | 336 | DE | 11011110 | Þ | Þ | Þ | Latin capital letter THORN |
223 | 337 | DF | 11011111 | ß | ß | ß | Latin small letter sharp s - ess-zed |
224 | 340 | E0 | 11100000 | à | à | à | Latin small letter a with grave |
225 | 341 | E1 | 11100001 | á | á | á | Latin small letter a with acute |
226 | 342 | E2 | 11100010 | â | â | â | Latin small letter a with circumflex |
227 | 343 | E3 | 11100011 | ã | ã | ã | Latin small letter a with tilde |
228 | 344 | E4 | 11100100 | ä | ä | ä | Latin small letter a with diaeresis |
229 | 345 | E5 | 11100101 | å | å | å | Latin small letter a with ring above |
230 | 346 | E6 | 11100110 | æ | æ | æ | Latin small letter ae |
231 | 347 | E7 | 11100111 | ç | ç | ç | Latin small letter c with cedilla |
232 | 350 | E8 | 11101000 | è | è | è | Latin small letter e with grave |
233 | 351 | E9 | 11101001 | é | é | é | Latin small letter e with acute |
234 | 352 | EA | 11101010 | ê | ê | ê | Latin small letter e with circumflex |
235 | 353 | EB | 11101011 | ë | ë | ë | Latin small letter e with diaeresis |
236 | 354 | EC | 11101100 | ì | ì | ì | Latin small letter i with grave |
237 | 355 | ED | 11101101 | í | í | í | Latin small letter i with acute |
238 | 356 | EE | 11101110 | î | î | î | Latin small letter i with circumflex |
239 | 357 | EF | 11101111 | ï | ï | ï | Latin small letter i with diaeresis |
240 | 360 | F0 | 11110000 | ð | ð | ð | Latin small letter eth |
241 | 361 | F1 | 11110001 | ñ | ñ | ñ | Latin small letter n with tilde |
242 | 362 | F2 | 11110010 | ò | ò | ò | Latin small letter o with grave |
243 | 363 | F3 | 11110011 | ó | ó | ó | Latin small letter o with acute |
244 | 364 | F4 | 11110100 | ô | ô | ô | Latin small letter o with circumflex |
245 | 365 | F5 | 11110101 | õ | õ | õ | Latin small letter o with tilde |
246 | 366 | F6 | 11110110 | ö | ö | ö | Latin small letter o with diaeresis |
247 | 367 | F7 | 11110111 | ÷ | ÷ | ÷ | Division sign |
248 | 370 | F8 | 11111000 | ø | ø | ø | Latin small letter o with slash |
249 | 371 | F9 | 11111001 | ù | ù | ù | Latin small letter u with grave |
250 | 372 | FA | 11111010 | ú | ú | ú | Latin small letter u with acute |
251 | 373 | FB | 11111011 | û | û | û | Latin small letter u with circumflex |
252 | 374 | FC | 11111100 | ü | ü | ü | Latin small letter u with diaeresis |
253 | 375 | FD | 11111101 | ý | ý | ý | Latin small letter y with acute |
254 | 376 | FE | 11111110 | þ | þ | þ | Latin small letter thorn |
255 | 377 | FF | 11111111 | ÿ | ÿ | ÿ | Latin small letter y with diaeresis |
Decimal | Octal | Hex | Bin | Symbol | HTML | Description |
---|---|---|---|---|---|---|
0 | 000 | 00 | 00000000 | NUL | � | Null character |
1 | 001 | 01 | 00000001 | SOH |  | Start of Heading |
2 | 002 | 02 | 00000010 | STX |  | Start of Text |
3 | 003 | 03 | 00000011 | ETX |  | End of Text |
4 | 004 | 04 | 00000100 | EOT |  | End of Transmission |
5 | 005 | 05 | 00000101 | ENQ |  | Enquiry |
6 | 006 | 06 | 00000110 | ACK |  | Acknowledge |
7 | 007 | 07 | 00000111 | BEL |  | Bell, Alert |
8 | 010 | 08 | 00001000 | BS |  | Backspace |
9 | 011 | 09 | 00001001 | HT | 	 | Horizontal Tab |
10 | 012 | 0A | 00001010 | LF | | Line Feed |
11 | 013 | 0B | 00001011 | VT |  | Vertical Tabulation |
12 | 014 | 0C | 00001100 | FF |  | Form Feed |
13 | 015 | 0D | 00001101 | CR | | Carriage Return |
14 | 016 | 0E | 00001110 | SO |  | Shift Out |
15 | 017 | 0F | 00001111 | SI |  | Shift In |
16 | 020 | 10 | 00010000 | DLE |  | Data Link Escape |
17 | 021 | 11 | 00010001 | DC1 |  | Device Control One (XON) |
18 | 022 | 12 | 00010010 | DC2 |  | Device Control Two |
19 | 023 | 13 | 00010011 | DC3 |  | Device Control Three (XOFF) |
20 | 024 | 14 | 00010100 | DC4 |  | Device Control Four |
21 | 025 | 15 | 00010101 | NAK |  | Negative Acknowledge |
22 | 026 | 16 | 00010110 | SYN |  | Synchronous Idle |
23 | 027 | 17 | 00010111 | ETB |  | End of Transmission Block |
24 | 030 | 18 | 00011000 | CAN |  | Cancel |
25 | 031 | 19 | 00011001 | EM |  | End of medium |
26 | 032 | 1A | 00011010 | SUB |  | Substitute |
27 | 033 | 1B | 00011011 | ESC |  | Escape |
28 | 034 | 1C | 00011100 | FS |  | File Separator |
29 | 035 | 1D | 00011101 | GS |  | Group Separator |
30 | 036 | 1E | 00011110 | RS |  | Record Separator |
31 | 037 | 1F | 00011111 | US |  | Unit Separator |
String Object
The String object is a wrapper around the string primitive data type.
const foo = new String("foo"); // Creates a String object console.log(foo); // [String: 'foo'] typeof foo; // 'object'
You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example:
const firstString = "2 + 2"; // CREATES A STRING LITERAL VALUE const secondString = new String("2 + 2"); // CREATES A STRING OBJECT eval(firstString); // RETURNS THE NUMBER 4 eval(secondString); // RETURNS A STRING OBJECT CONTAINING "2 + 2"
Creating Strings
Strings can be created as primitives, from string literals, or as objects, using the String() constructor:
const string1 = "A string primitive"; // DOUBLE QUOTES const string2 = 'Also a string primitive'; // SINGLE QUOTES const string3 = `Yet another string primitive`; // TEMPLATE LITERAL
Character Access
var s = "A string of characters"; var c = s.charAt(0); // c = 'A'
Comparing Strings
Use the less-than and greater-than operators to compare strings:
const a = "a"; const b = "b"; if (a < b) { // TRUE console.log(`${a} is less than ${b}`); } else if (a > b) { console.log(`${a} is greater than ${b}`); } else { console.log(`${a} and ${b} are equal.`); }
Method | Description |
---|---|
charAt() charCodeAt() codePointAt() |
Return the character or character code at the specified position in string. |
indexOf() lastIndexOf() |
Return the position of specified substring in the string or last position of specified substring, respectively. |
startsWith() endsWith() includes() |
Returns whether or not the string starts, ends or contains a specified string. |
concat() | Combines the text of two strings and returns a new string. |
split() | Splits a String object into an array of strings by separating the string into substrings. |
slice() | Extracts a section of a string and returns a new string. |
substring() substr() |
Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length. |
match() matchAll() replace() replaceAll() search() |
Work with regular expressions. |
toLowerCase() toUpperCase() |
Return the string in all lowercase or all uppercase, respectively. |
normalize() | Returns the Unicode Normalization Form of the calling string value. |
repeat() | Returns a string consisting of the elements of the object repeated the given times. |
trim() | Trims whitespace from the beginning and end of the string. |
charAt()
The charAt() method of String values returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.
const sentence = 'The quick brown fox jumps over the lazy dog.'; const index = 4; let myStr = ""; myStr = `The character at index ${index} is ${sentence.charAt(index)}`; // EXPECTED OUTPUT: "The character at index 4 is q"
charCodeAt()
The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
The UTF-16 code unit matches the Unicode code point for code points which can be represented in a single UTF-16 code unit.
If the Unicode code point cannot be represented in a single UTF-16 code unit (because its value is greater than 0xFFFF)
then the code unit returned will be the first part of a surrogate pair for the code point. If you want the entire code
point value, use codePointAt().
const sentence = 'The quick brown fox jumps over the lazy dog.'; const index = 4; let myStr = ""; myStr = `The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`; // EXPECTED OUTPUT: "The character code 113 is equal to q"
codePointAt()
The codePointAt() method returns a non-negative integer that is the Unicode code point value at the given position. Note that this function does not give the nth code point in a string, but the code point starting at the specified string index.
const icons = '☃★♲'; let myStr = ""; myStr = icons.codePointAt(1); // EXPECTED OUTPUT: "9733"
indexOf()
The indexOf() method of String values searches this string and returns the index of the first occurrence of the specified substring. It takes an optional starting position and returns the first occurrence of the specified substring at an index greater than or equal to the specified number.
The search is case sensitive
indexOf(searchString) indexOf(searchString, position)
searchString
Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string "undefined", which is rarely what you want.
position
Optional parameter. The method returns the index of the first occurrence of the specified substring at a position greater than or equal to position, which defaults to 0. If position is greater than the length of the calling string, the method doesn't search the calling string at all. If position is less than zero, the method behaves as it would if position were 0.
Return Value
The index of the first occurrence of searchString found, or -1 if not found.
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; const searchTerm = 'dog'; const indexOfFirst = paragraph.indexOf(searchTerm); let myStr = ""; myStr = `The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`; // EXPECTED OUTPUT: "The index of the first "dog" from the beginning is 40" myStr = `The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`; // EXPECTED OUTPUT: "The index of the 2nd "dog" is 52"
lastIndexOf()
The lastIndexOf() method of String values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.
lastIndexOf(searchString) lastIndexOf(searchString, position)
searchString
Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string "undefined", which is rarely what you want.
position
Optional parameter. The method returns the index of the last occurrence of the specified substring at a position less than or equal to position, which defaults to +Infinity. If position is greater than the length of the calling string, the method searches the entire string. If position is less than 0, the behavior is the same as for 0 — that is, the method looks for the specified substring only at index 0.
Return Value
The index of the last occurrence of searchString found, or -1 if not found.
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; const searchTerm = 'dog'; let myStr = ""; myStr = `The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(searchTerm)}`; // EXPECTED OUTPUT: "The index of the first "dog" from the end is 52"
startsWith()
The startsWith() method determines whether a string begins with the characters of a specified string, returning true or false as appropriate.
startsWith(searchString) startsWith(searchString, position)
searchString
The characters to be searched for at the start of this string. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes startsWith() to search for the string "undefined", which is rarely what you want.
position
Optional parameter. The start position at which searchString is expected to be found (the index of searchString's first character). Defaults to 0.
Return Value
true if the given characters are found at the beginning of the string, including when searchString is an empty string; otherwise, false.
const str1 = 'Saturday night plans'; let outStr = ""; outStr = str1.startsWith('Sat'); // EXPECTED OUTPUT: true outStr = str1.startsWith('Sat', 3); // EXPECTED OUTPUT: false
endsWith()
The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate.
endsWith(searchString) endsWith(searchString, endPosition)
searchString
The characters to be searched for at the end of str. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes endsWith() to search for the string "undefined", which is rarely what you want.
endPosition
Optional parameter. The end position at which searchString is expected to be found (the index of searchString's last character plus 1). Defaults to str.length.
Return Value
true if the given characters are found at the end of the string, including when searchString is an empty string; otherwise, false.
let myStr = ""; const str1 = 'Cats are the best!'; console.log(str1.endsWith('best!')); // Expected output: true console.log(str1.endsWith('best', 17)); // Expected output: true const str2 = 'Is this a question?'; console.log(str2.endsWith('question')); // Expected output: false
includes()
The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate.
includes(searchString) includes(searchString, position)
searchString
A string to be searched for within str. Cannot be a regex. All values that are not regexes are coerced to strings, so omitting it or passing undefined causes includes() to search for the string "undefined", which is rarely what you want.
position
The position within the string at which to begin searching for searchString. (Defaults to 0.)
Return Value
true if the search string is found anywhere within the given string, including when searchString is an empty string; otherwise, false.
const sentence = 'The quick brown fox jumps over the lazy dog.'; const word = 'fox'; outStr = `The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`; // EXPECTED OUTPUT: "The word "fox" is in the sentence"
concat()
The concat() method concatenates the string arguments to the calling string and returns a new string.
strN
One or more strings to concatenate to str.
Return Value
A new string containing the combined text of the strings provided.
concat(str1) concat(str1, str2) concat(str1, str2, /* ..., */ strN)
const str1 = 'Hello'; const str2 = 'World'; outStr = str1.concat(' ', str2); // EXPECTED OUTPUT: "Hello World" outStr = str2.concat(', ', str1); // EXPECTED OUTPUT: "World, Hello"
split()
The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
split(separator) split(separator, limit)
separator
The pattern describing where each split should occur. Can be undefined, a string, or an object with a Symbol.split method, the typical example being a regular expression. Omitting separator or passing undefined causes split() to return an array with the calling string as a single element. All values that are not undefined or objects with a @@split method are coerced to strings.
limit
Optional parameter. A non-negative integer specifying a limit on the number of substrings to be included in the array. If provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. Any leftover text is not included in the array at all.
Return Value
An Array of strings, split at each point where the separator occurs in the given string.
const str = 'The quick brown fox jumps over the lazy dog.'; const words = str.split(' '); const chars = str.split(''); const strCopy = str.split(); outStr = words[3]; // EXPECTED OUTPUT: "fox" outStr = chars[8]; // EXPECTED OUTPUT: "k" outStr = strCopy; // EXPECTED OUTPUT: Array ["The quick brown fox jumps over the lazy dog."]
slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
slice(indexStart) slice(indexStart, indexEnd)
indexStart
The index of the first character to include in the returned substring.
indexEnd
The index of the first character to exclude from the returned substring.
Return Value
A new string containing the extracted section of the string.
const str = 'The quick brown fox jumps over the lazy dog.'; outStr = str.slice(31); // EXPECTED OUTPUT: "the lazy dog." outStr = str.slice(4, 19); // EXPECTED OUTPUT: "quick brown fox" outStr = str.slice(-4); // EXPECTED OUTPUT: "dog." outStr = str.slice(-9, -5); // EXPECTED OUTPUT: "lazy"
substring()
The substring() method returns the part of the string from the start index up to and excluding the end index, or to the end of the string if no end index is supplied.
substring(indexStart) substring(indexStart, indexEnd)
indexStart
The index of the first character to include in the returned substring.
indexEnd
The index of the first character to exclude from the returned substring.
Return Value
A new string containing the specified part of the given string.
const str = 'Jazz Butcher'; outStr = str.substring(1, 3); // EXPECTED OUTPUT: "az" outStr = str.substring(2); // EXPECTED OUTPUT: "zz Butcher"
substr()
This method has been Depreciated
match()
The match() method retrieves the result of matching a string against a regular expression.
match(regexp)
regexp
A regular expression object, or any object that has a Symbol.match method.
If regexp is not a RegExp object and does not have a Symbol.match method, it is implicitly converted to a RegExp by using new RegExp(regexp).
If you don't give any parameter and use the match() method directly, you will get an Array with an empty string: [""], because this is equivalent to match(/(?:)/).
Return Value
An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.
- If the g flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included.
- If the g flag is not used, only the first complete match and its related capturing groups are returned. In this case, match() will return the same result as RegExp.prototype.exec() (an array with some extra properties).
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/g; // ALL CAPITAL LETTERS, GLOBAL SEARCH const found = paragraph.match(regex); outStr = found; // EXPECTED OUTPUT: Array ["T", "I"]
matchAll()
The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups.
matchAll(regexp)
regexp
A regular expression object, or any object that has a Symbol.matchAll method.
If regexp is not a RegExp object and does not have a Symbol.matchAll method, it is implicitly converted to a RegExp by using new RegExp(regexp, 'g').
If regexp is a regex, then it must have the global (g) flag set, or a TypeError is thrown.
Return Value
An iterable iterator object (which is not restartable) of matches. Each match is an array with the same shape as the return value of RegExp.prototype.exec().
const regexp = /t(e)(st(\d?))/g; const str = 'test1test2'; const array = [...str.matchAll(regexp)]; outStr = array[0]; // EXPECTED OUTPUT: Array ["test1", "e", "st1", "1"] outStr = array[1]; // EXPECTED OUTPUT: Array ["test2", "e", "st2", "2"]
replace()
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced. The original string is left unchanged.
replace(pattern, replacement)
pattern
Can be a string or an object with a Symbol.replace method, the typical example being a
regular expression.
Any value that doesn't have the Symbol.replace method will be coerced
to a string.
replacement
Can be a string or a function.
- If it's a string, it will replace the substring matched by pattern. A number of special replacement patterns are supported.
- If it's a function, it will be invoked for every match and its return value is used as the replacement text.
Return Value
A new string, with one, some, or all matches of the pattern replaced by the specified replacement.
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; outStr = p.replace('dog', 'monkey'); // EXPECTED OUTPUT: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?" const regex = /Dog/i; outStr = p.replace(regex, 'ferret'); // EXPECTED OUTPUT: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
replaceAll()
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
replaceAll(pattern, replacement)
pattern
Can be a string or an object with a Symbol.replace method, the typical example being a regular expression. Any value that doesn't have the Symbol.replace method will be coerced to a string.
If pattern is a regex, then it must have the global (g) flag set, or a TypeError is thrown.
replacement
Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace().
Return Value
A new string, with all matches of a pattern replaced by a replacement.
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; outStr = p.replaceAll('dog', 'monkey'); // EXPECTED OUTPUT: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?" // GLOBAL FLAG REQUIRED WHEN CALLING replaceAll WITH regex const regex = /Dog/ig; outstr = p.replaceAll(regex, 'ferret'); // EXPECTED OUTPUT: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
search()
The search() method executes a search for a match between a regular expression and this String object.
search(regexp)
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; // ANY CHARACTER THAT IS NOT A WORD CHARACTER OR WHITESPACE const regex = /[^\w\s]/g; outStr = paragraph.search(regex); // EXPECTED OUTPUT: 43 outStr = paragraph[paragraph.search(regex)]; // EXPECTED OUTPUT: "."
toLowerCase()
The toLowerCase() method returns the calling string value converted to lower case.
toLowerCase()
const sentence = 'The quick brown fox jumps over the lazy dog.'; outStr = sentence.toLowerCase(); // EXPECTED OUTPUT: "the quick brown fox jumps over the lazy dog."
toUpperCase()
The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
toUpperCase()
const sentence = 'The quick brown fox jumps over the lazy dog.'; outStr = sentence.toUpperCase(); // EXPECTED OUTPUT: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
normalize()
The normalize() method returns the Unicode Normalization Form of the string.
Unicode assigns a unique numerical value, called a code point, to each character.
For example, the code point for A is given as U+0041.
However, sometimes more than one code point, or sequence of code points,
can represent the same abstract character, the character ñ for example can be represented by either of:
- The single code point U+00F1.
- The code point for n (U+006E) followed by the code point for the combining tilde (U+0303).
Unicode Characters
normalize() normalize(form)
form
Optional parameter. One of "NFC", "NFD", "NFKC", or "NFKD", specifying the Unicode Normalization Form. If omitted or undefined, "NFC" is used.
These values have the following meanings:
- NFC - Canonical Decomposition, followed by Canonical Composition.
- NFD - Canonical Decomposition.
- NFKC - Compatibility Decomposition, followed by Canonical Composition.
- NFKD - Compatibility Decomposition.
Return Value
A string containing the Unicode Normalization Form of the given string.
const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065'; const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065'; outStr = `${name1}, ${name2}`; // EXPECTED OUTPUT: "Amélie, Amélie" outStr = name1 === name2; // EXPECTED OUTPUT: false outStr = name1.length === name2.length; // EXPECTED OUTPUT: false const name1NFC = name1.normalize('NFC'); const name2NFC = name2.normalize('NFC'); outStr = `${name1NFC}, ${name2NFC}`; // EXPECTED OUTPUT: "Amélie, Amélie" outStr = name1NFC === name2NFC; // EXPECTED OUTPUT: true outStr = name1NFC.length === name2NFC.length; // EXPECTED OUTPUT: true
repeat()
The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
repeat(count)
count
An integer between 0 and +Infinity, indicating the number of times to repeat the string.
Return Value
A new string containing the specified number of copies of the given string.
const mood = 'Happy! '; outStr = `I feel ${mood.repeat(3)}`; // EXPECTED OUTPUT: "I feel Happy! Happy! Happy! "
trim()
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string.
To return a new string with whitespace trimmed from just one end, use trimStart() or trimEnd().
trim()
const greeting = ' Hello world! '; outStr = greeting; // EXPECTED OUTPUT: " Hello world! "; outStr = greeting.trim(); // EXPECTED OUTPUT: "Hello world!";
trimStart()
The trimStart() method removes whitespace from the beginning of a string and returns a new string, without modifying the original string. trimLeft() is an alias of this method.
trimStart() trimLeft()
const greeting = ' Hello world! '; outStr = greeting; // EXPECTED OUTPUT: " Hello world! "; outStr = greeting.trimStart(); // EXPECTED OUTPUT: "Hello world! ";
trimEnd()
The trimEnd() method removes whitespace from the end of a string and returns a new string, without modifying the original string. trimRight() is an alias of this method.
trimEnd() trimRight()
const greeting = ' Hello world! '; outStr = greeting; // EXPECTED OUTPUT: " Hello world! "; outStr = greeting.trimEnd(); // EXPECTED OUTPUT: " Hello world!";
Template Literals
Template literals are string literals allowing embedded expressions.
You can use multi-line strings and string interpolation features with them.
Template literals are enclosed by backtick (grave accent) characters (`)
instead of double or single quotes. Template literals can contain placeholders.
These are indicated by the dollar sign and curly braces (${expression}).
Multi-Line Template Literals
var s = `string text line 1 string text line 2`; // "string text line 1 // string text line 2"
Embedded Expressions
function runScript2() {
let resultDiv = document.getElementById("results2");
const five = 5;
const ten = 10;
const s1 = "Fifteen is " + (five + ten) + " and not " + (2 * five + ten) + ".";
// "Fifteen is 15 and not 20."
const s2 = `Fifteen is ${five + ten} and not ${2 * five + ten}.`;
// "Fifteen is 15 and not 20."
resultDiv.innerHTML = s1 +"
"+ s2;
}
Run Script