Dirk Harriman Banner Image

 

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.

Escape Characters
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.

Parameters
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 Script
 

 

Character Sets

Printable Character Set
Decimal Octal Hex Bin Symbol HTML Name Description
32 0402000100000SP &#32; Space
33 0412100100001! &#33; &excl; Exclamation mark
34 0422200100010" &#34; &quot; Double quotes (or speech marks)
35 0432300100011# &#35; &num; Number sign
36 0442400100100$ &#36; &dollar;Dollar
37 0452500100101% &#37; &percnt;Per cent sign
38 0462600100110& &#38; &amp; Ampersand
39 0472700100111' &#39; &apos; Single quote
40 0502800101000( &#40; &lparen;Open parenthesis (or open bracket)
41 0512900101001) &#41; &rparen;Close parenthesis (or close bracket)
42 0522A00101010* &#42; &ast; Asterisk
43 0532B00101011+ &#43; &plus; Plus
44 0542C00101100, &#44; &comma; Comma
45 0552D00101101- &#45; Hyphen-minus
46 0562E00101110. &#46; &period;Period, dot or full stop
47 0572F00101111/ &#47; &sol; Slash or divide
48 06030001100000 &#48; Zero
49 06131001100011 &#49; One
50 06232001100102 &#50; Two
51 06333001100113 &#51; Three
52 06434001101004 &#52; Four
53 06535001101015 &#53; Five
54 06636001101106 &#54; Six
55 06737001101117 &#55; Seven
56 07038001110008 &#56; Eight
57 07139001110019 &#57; Nine
58 0723A00111010: &#58; &colon; Colon
59 0733B00111011; &#59; &semi; Semicolon
60 0743C00111100< &#60; &lt; Less than (or open angled bracket)
61 0753D00111101= &#61; &equals;Equals
62 0763E00111110> &#62; &gt; Greater than (or close angled bracket)
63 0773F00111111? &#63; &quest; Question mark
64 1004001000000@ &#64; &commat;At sign
65 1014101000001A &#65; Uppercase A
66 1024201000010B &#66; Uppercase B
67 1034301000011C &#67; Uppercase C
68 1044401000100D &#68; Uppercase D
69 1054501000101E &#69; Uppercase E
70 1064601000110F &#70; Uppercase F
71 1074701000111G &#71; Uppercase G
72 1104801001000H &#72; Uppercase H
73 1114901001001I &#73; Uppercase I
74 1124A01001010J &#74; Uppercase J
75 1134B01001011K &#75; Uppercase K
76 1144C01001100L &#76; Uppercase L
77 1154D01001101M &#77; Uppercase M
78 1164E01001110N &#78; Uppercase N
79 1174F01001111O &#79; Uppercase O
80 1205001010000P &#80; Uppercase P
81 1215101010001Q &#81; Uppercase Q
82 1225201010010R &#82; Uppercase R
83 1235301010011S &#83; Uppercase S
84 1245401010100T &#84; Uppercase T
85 1255501010101U &#85; Uppercase U
86 1265601010110V &#86; Uppercase V
87 1275701010111W &#87; Uppercase W
88 1305801011000X &#88; Uppercase X
89 1315901011001Y &#89; Uppercase Y
90 1325A01011010Z &#90; Uppercase Z
91 1335B01011011[ &#91; &lsqb; Opening bracket
92 1345C01011100\ &#92; &bsol; Backslash
93 1355D01011101] &#93; &rsqb; Closing bracket
94 1365E01011110^ &#94; &Hat; Caret - circumflex
95 1375F01011111_ &#95; &lowbar;Underscore
96 1406001100000` &#96; &grave; Grave accent
97 1416101100001a &#97; Lowercase a
98 1426201100010b &#98; Lowercase b
99 1436301100011c &#99; Lowercase c
1001446401100100d &#100; Lowercase d
1011456501100101e &#101; Lowercase e
1021466601100110f &#102; Lowercase f
1031476701100111g &#103; Lowercase g
1041506801101000h &#104; Lowercase h
1051516901101001i &#105; Lowercase i
1061526A01101010j &#106; Lowercase j
1071536B01101011k &#107; Lowercase k
1081546C01101100l &#108; Lowercase l
1091556D01101101m &#109; Lowercase m
1101566E01101110n &#110; Lowercase n
1111576F01101111o &#111; Lowercase o
1121607001110000p &#112; Lowercase p
1131617101110001q &#113; Lowercase q
1141627201110010r &#114; Lowercase r
1151637301110011s &#115; Lowercase s
1161647401110100t &#116; Lowercase t
1171657501110101u &#117; Lowercase u
1181667601110110v &#118; Lowercase v
1191677701110111w &#119; Lowercase w
1201707801111000x &#120; Lowercase x
1211717901111001y &#121; Lowercase y
1221727A01111010z &#122; Lowercase z
1231737B01111011{ &#123;&lcub; Opening brace
1241747C01111100| &#124;&verbar;Vertical bar
1251757D01111101} &#125;&rcub; Closing brace
1261767E01111110~ &#126;&tilde; Equivalency sign - tilde
1271777F01111111DEL&#127; Delete

 
Extended Character Set
Decimal Octal Hex Bin Symbol HTML Name Description
1282008010000000&#8364;Euro sign
1292018110000001 Unused
1302028210000010&#130;&sbquo; Single low-9 quotation mark
1312038310000011ƒ &#131;&fnof; Latin small letter f with hook
1322048410000100&#132;&bdquo; Double low-9 quotation mark
1332058510000101&#133;&hellip;Horizontal ellipsis
1342068610000110&#134;&dagger;Dagger
1352078710000111&#135;&Dagger;Double dagger
1362108810001000ˆ&#136;&circ; Modifier letter circumflex accent
1372118910001001&#137;&permil;Per mille sign
1382128A10001010Š &#138;&Scaron;Latin capital letter S with caron
1392138B10001011&#139;&lsaquo;Single left-pointing angle quotation
1402148C10001100Π&#140;&OElig; Latin capital ligature OE
1412158D10001101 Unused
1422168E10001110Ž &#142;&Zcaron;Latin capital letter Z with caron
1432178F10001111 Unused
1442209010010000 Unused
1452219110010001&#145;&lsquo; Left single quotation mark
1462229210010010&#146;&rsquo; Right single quotation mark
1472239310010011&#147;&ldquo; Left double quotation mark
1482249410010100&#148;&rdquo; Right double quotation mark
1492259510010101&#149;&bull; Bullet
1502269610010110&#150;&ndash; En dash
1512279710010111&#151;&mdash; Em dash
1522309810011000˜&#152;&tilde; Small tilde
1532319910011001&#153;&trade; Trade mark sign
1542329A10011010š &#154;&scaron;Latin small letter S with caron
1552339B10011011&#155;&rsaquo;Single right-pointing angle quotation mark
1562349C10011100œ &#156;&oelig; Latin small ligature oe
1572359D10011101 Unused
1582369E10011110ž &#158;&zcaron;Latin small letter z with caron
1592379F10011111Ÿ &#159;&Yuml; Latin capital letter Y with diaeresis
160240A010100000NBSP &#160;&nbsp; Non-breaking space
161241A110100001¡ &#161;&iexcl; Inverted exclamation mark
162242A210100010¢ &#162;&cent; Cent sign
163243A310100011£ &#163;&pound; Pound sign
164244A410100100¤ &#164;&curren;Currency sign
165245A510100101¥ &#165;&yen; Yen sign
166246A610100110¦ &#166;&brvbar;Pipe, broken vertical bar
167247A710100111§ &#167;&sect; Section sign
168250A810101000¨ &#168;&uml; Spacing diaeresis - umlaut
169251A910101001© &#169;&copy; Copyright sign
170252AA10101010ª &#170;&ordf; Feminine ordinal indicator
171253AB10101011« &#171;&laquo; Left double angle quotes
172254AC10101100¬ &#172;&not; Negation
173255AD10101101SHY&#173;&shy;Soft hyphen
174256AE10101110® &#174;&reg; Registered trade mark sign
175257AF10101111¯ &#175;&macr; Spacing macron - overline
176260B010110000° &#176;&deg; Degree sign
177261B110110001± &#177;&plusmn;Plus-or-minus sign
178262B210110010² &#178;&sup2; Superscript two - squared
179263B310110011³ &#179;&sup3; Superscript three - cubed
180264B410110100´ &#180;&acute; Acute accent - spacing acute
181265B510110101µ &#181;&micro; Micro sign
182266B610110110&#182;&para; Pilcrow sign - paragraph sign
183267B710110111· &#183;&middot;Middle dot - Georgian comma
184270B810111000¸&#184;&cedil; Spacing cedilla
185271B910111001¹ &#185;&sup1; Superscript one
186272BA10111010º &#186;&ordm; Masculine ordinal indicator
187273BB10111011» &#187;&raquo; Right double angle quotes
188274BC10111100¼ &#188;&frac14;Fraction one quarter
189275BD10111101½ &#189;&frac12;Fraction one half
190276BE10111110¾ &#190;&frac34;Fraction three quarters
191277BF10111111¿ &#191;&iquest;Inverted question mark
192300C011000000À &#192;&Agrave;Latin capital letter A with grave
193301C111000001Á &#193;&Aacute;Latin capital letter A with acute
194302C211000010Â &#194;&Acirc; Latin capital letter A with circumflex
195303C311000011Ã &#195;&Atilde;Latin capital letter A with tilde
196304C411000100Ä &#196;&Auml; Latin capital letter A with diaeresis
197305C511000101Å &#197;&Aring; Latin capital letter A with ring above
198306C611000110Æ &#198;&AElig; Latin capital letter AE
199307C711000111Ç &#199;&Ccedil;Latin capital letter C with cedilla
200310C811001000È &#200;&Egrave;Latin capital letter E with grave
201311C911001001É &#201;&Eacute;Latin capital letter E with acute
202312CA11001010Ê &#202;&Ecirc; Latin capital letter E with circumflex
203313CB11001011Ë &#203;&Euml; Latin capital letter E with diaeresis
204314CC11001100Ì &#204;&Igrave;Latin capital letter I with grave
205315CD11001101Í &#205;&Iacute;Latin capital letter I with acute
206316CE11001110Î &#206;&Icirc; Latin capital letter I with circumflex
207317CF11001111Ï &#207;&Iuml; Latin capital letter I with diaeresis
208320D011010000Ð &#208;&ETH; Latin capital letter ETH
209321D111010001Ñ &#209;&Ntilde;Latin capital letter N with tilde
210322D211010010Ò &#210;&Ograve;Latin capital letter O with grave
211323D311010011Ó &#211;&Oacute;Latin capital letter O with acute
212324D411010100Ô &#212;&Ocirc; Latin capital letter O with circumflex
213325D511010101Õ &#213;&Otilde;Latin capital letter O with tilde
214326D611010110Ö &#214;&Ouml; Latin capital letter O with diaeresis
215327D711010111×&#215;&times; Multiplication sign
216330D811011000Ø &#216;&Oslash;Latin capital letter O with slash
217331D911011001Ù &#217;&Ugrave;Latin capital letter U with grave
218332DA11011010Ú &#218;&Uacute;Latin capital letter U with acute
219333DB11011011Û &#219;&Ucirc; Latin capital letter U with circumflex
220334DC11011100Ü &#220;&Uuml; Latin capital letter U with diaeresis
221335DD11011101Ý &#221;&Yacute;Latin capital letter Y with acute
222336DE11011110Þ &#222;&THORN; Latin capital letter THORN
223337DF11011111ß &#223;&szlig; Latin small letter sharp s - ess-zed
224340E011100000à &#224;&agrave;Latin small letter a with grave
225341E111100001á &#225;&aacute;Latin small letter a with acute
226342E211100010â &#226;&acirc; Latin small letter a with circumflex
227343E311100011ã &#227;&atilde;Latin small letter a with tilde
228344E411100100ä &#228;&auml; Latin small letter a with diaeresis
229345E511100101å &#229;&aring; Latin small letter a with ring above
230346E611100110æ &#230;&aelig; Latin small letter ae
231347E711100111ç &#231;&ccedil;Latin small letter c with cedilla
232350E811101000è &#232;&egrave;Latin small letter e with grave
233351E911101001é &#233;&eacute;Latin small letter e with acute
234352EA11101010ê &#234;&ecirc; Latin small letter e with circumflex
235353EB11101011ë &#235;&euml; Latin small letter e with diaeresis
236354EC11101100ì &#236;&igrave;Latin small letter i with grave
237355ED11101101í &#237;&iacute;Latin small letter i with acute
238356EE11101110î &#238;&icirc; Latin small letter i with circumflex
239357EF11101111ï &#239;&iuml; Latin small letter i with diaeresis
240360F011110000ð &#240;&eth; Latin small letter eth
241361F111110001ñ &#241;&ntilde;Latin small letter n with tilde
242362F211110010ò &#242;&ograve;Latin small letter o with grave
243363F311110011ó &#243;&oacute;Latin small letter o with acute
244364F411110100ô &#244;&ocirc; Latin small letter o with circumflex
245365F511110101õ &#245;&otilde;Latin small letter o with tilde
246366F611110110ö &#246;&ouml; Latin small letter o with diaeresis
247367F711110111÷ &#247;&divide;Division sign
248370F811111000ø &#248;&oslash;Latin small letter o with slash
249371F911111001ù &#249;&ugrave;Latin small letter u with grave
250372FA11111010ú &#250;&uacute;Latin small letter u with acute
251373FB11111011û &#251;&ucirc; Latin small letter u with circumflex
252374FC11111100ü &#252;&uuml; Latin small letter u with diaeresis
253375FD11111101ý &#253;&yacute;Latin small letter y with acute
254376FE11111110þ &#254;&thorn; Latin small letter thorn
255377FF11111111ÿ &#255;&yuml; Latin small letter y with diaeresis

 
Control Character Set
Decimal Octal Hex Bin Symbol HTML Description
0 0000000000000NUL&#00;Null character
1 0010100000001SOH&#01;Start of Heading
2 0020200000010STX&#02;Start of Text
3 0030300000011ETX&#03;End of Text
4 0040400000100EOT&#04;End of Transmission
5 0050500000101ENQ&#05;Enquiry
6 0060600000110ACK&#06;Acknowledge
7 0070700000111BEL&#07;Bell, Alert
8 0100800001000BS &#08;Backspace
9 0110900001001HT &#09;Horizontal Tab
100120A00001010LF &#10;Line Feed
110130B00001011VT &#11;Vertical Tabulation
120140C00001100FF &#12;Form Feed
130150D00001101CR &#13;Carriage Return
140160E00001110SO &#14;Shift Out
150170F00001111SI &#15;Shift In
160201000010000DLE&#16;Data Link Escape
170211100010001DC1&#17;Device Control One (XON)
180221200010010DC2&#18;Device Control Two
190231300010011DC3&#19;Device Control Three (XOFF)
200241400010100DC4&#20;Device Control Four
210251500010101NAK&#21;Negative Acknowledge
220261600010110SYN&#22;Synchronous Idle
230271700010111ETB&#23;End of Transmission Block
240301800011000CAN&#24;Cancel
250311900011001EM &#25;End of medium
260321A00011010SUB&#26;Substitute
270331B00011011ESC&#27;Escape
280341C00011100FS &#28;File Separator
290351D00011101GS &#29;Group Separator
300361E00011110RS &#30;Record Separator
310371F00011111US &#31;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.`); }


 
String Methods
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.

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.

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:

 
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:

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
 

 

Run Script