Open CheatSheet Back To List Next Tutorial

Strings

Intro

  • This tutorial covers JavaScript Strings.

  • It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar. 

  • The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.


1. Create a string.

  • Strings are just a sequence of characters. You can create a string literal by surrounding the characters with quotes. You can use single or double quotes. Style guides recommend single quotes.
  • String literal: A string literal is a literal string of characters: 'This is a string literal.'; 
  • String data type: String is a JavaScript primitive data type: typeof 'Some text'; // returns 'string'
  • Variable: You can assign a string to a variable where it is stored for later use or reuse: 
    • let str = 'This is a string variable';
  • Immutable: Strings are immutable meaning they can't be changed. When you assign a variable to a string then change the value, you are not changing the string. Rather you are creating a new string and assigning the variable to this new string. The old string gets discarded.

String Escape Notation:
  • String escape notation allows you to insert characters with special meaning. \t adds a tab. \n adds a new line. And \ lets you escape quotation marks so that you can use them in your string.
str = '\tString escape notation. Don\'t forget to escape apostophes.\nThen start a new line.';

    • Tab (\t): The above example starts with a \t tab character which indents the line.
    • Escape character (\): A backslash escapes the apostrophe in the word "don\'t", otherwise it would have ended the string right there. 
      • Another option is to put the string in double quotes, then you don't need to escape single quotes.
    • Newline (\n): The newline character \n creates a new line.

Template literals
  • Template literals (aka template strings) are enclosed in backticks instead of quotes.
  • They allow you to insert JavaScript expressions in your string by using a dollar sign and curly braces. This is called interpolation. 
  • You can also use multiple lines without having to insert the \n newline notation.
Format: `Text ${expression}` 
Example:
const myVar = 'interpolation';
str = `Template strings allow ${myVar}.
And multiline strings.`; str; // returns: "Template strings allow interpolation. And multiline strings."

String object
  • You can also create strings as objects by calling the String constructor function with the new operator, passing in the string value. String literals are preferred over string objects.
const strObj = new String('This is a string object');
typeof strObj; // returns 'object'
const strLit = 'This is a string literal';
typeof strLit; // returns 'string'


2. The String standard built-in object

  • Sting is a standard built in object on the global scope:
String === window.String; // returns true from the browser
String === global.String; // returns true from Node.js

  • String is a function (functions are a type of object).
typeof String; // returns 'function'

  • When called in a non-constructor context (i.e., without the new keyword) it converts the argument to a string primitive value:
String(10); // returns '10'
String(true); // returns 'true'

Static properties and methods:
  • String has six static properties including methods:
Object.getOwnPropertyNames(String); // returns length, name, prototype, fromCharCode, fromCodePoint, raw
You likely won't use these often if at all so we will only cover one. 

  • Static methods are called on the String function itself, not on a string instance. The fromCharCode method takes UTF-16 character encoding as input. Each number represents a character. And returns their character string as output. In the below example we pass in the character encoding for "Hello world"

let str = String.fromCharCode(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100);
str; // returns "Hello world"

String.prototype:
  • Prototype property: When the String function is used as a constructor with the new operator, it becomes the new object's prototype.
  • Constructor: The constructor function instantiates a new String object when called with the new keyword:
const str = new String('Hello');
typeof str; // returns 'object'
  • String literals are preferred over string objects.

String instance properties and methods:
  • The prototype of a string value is String.prototype:
Object.getPrototypeOf('Some text') === String.prototype; // returns true

  • String acts as a wrapper around string primitives. JavaScript automatically converts primitive string values to a String object when an instance method is called them.
  • String.prototype contains a large number of properties and methods you can call on a string instance. Below is the full list. This tutorial covers the most commonly used.
Object.getOwnPropertyNames(String.prototype); // Returns: length, constructor, anchor, big, blink, bold, charAt, charCodeAt, codePointAt, concat, endsWith, fontcolor, fontsize, fixed, includes, indexOf, italics, lastIndexOf, link, localeCompare, match, matchAll, normalize, padEnd, padStart, repeat, replace, replaceAll, search, slice, small, split, strike, sub, substr, substring, sup, startsWith, toString, trim, trimStart, trimLeft, trimEnd, trimRight, toLocaleLowerCase, toLocaleUpperCase, toLowerCase, toUpperCase, valueOf, at.


3. Return a modified copy of the string

Instance properties
String.prototype.length
  • Instance properties apply to a string instance.
  • The length property returns the number of characters in the string. 
  • Chain the length property to a string literal or variable and it will return the number of characters in the string (including spaces and special characters).
let len = "hello world".length; // returns 11

let str = "hello world";
len = str.length; // returns 11

Instance Methods: Return a modified copy of the string
  • Instance methods are functions applied to a string instance. The below instance methods return a modified copy of the string. 

String.prototype.toUpperCase()
  • ToUpperCase is an instance method that returns a copy of the string in all upper case letters. Chain the method to a string literal or variable.
  • Primitive values, including strings, are immutable so you can't change the actual value of the string. Instead, string methods return a modified copy of the string.
let str = 'Hello world';
let newStr = str.toUpperCase(); newStr; // returns "HELLO WORLD"
str; // returns "Hello world";

  • In the above example, the toUpperCase method returns a copy of the str value with all letters in upper case. We assigned the result to a different variable name newStr. The str variable contains the original value.

  • To change the str value you need to assign the result back to the str variable.
str = str.toUpperCase();
str; // returns "HELLO WORLD"

String.prototype.toLowerCase()
  • The toLowerCase method returns all lowercase letters.
str = str.toLowerCase();
str; // returns "hello world"

String.prototype.padStart(targetLength [, padString])
  • PadStart specifies the number of characters in the string and pads the start of the string with spaces if the string has fewer characters than the target Length.
str = str.padStart(13); // returns "  hello world"
let str2 = 'text'.padStart(10, '-'); // returns "------text"

  • The above example calls padStart on the str variable with an argument of 13. The str value, "hello world", has 11 characters. That is two less than our argument, so two spaces are added to the start of the string.
  • The second example chains the method to a string literal. The optional second argument provides a dash as the pad string.

String.prototype.trim()
  • Trim removes spaces from the beginning and end of a string. 
str; // returns "  hello world"
str = str.trim(); // returns "hello world"

String.prototype.charAt(index)
  • CharAt takes an index value as the argument and returns the character at the index value provided. This method treats the string as an array-like object which is zero-indexed.
let view = str.charAt(0); // returns "h"

String.prototype.slice(beginIndex[, endIndex])
  • Slice returns a substring starting with the index in the first argument, ending at the index in the second argument. If there is no second argument the substring goes to the end.
view = str.slice(1); // returns "ello world"

  • In the above example we use index 1 for the first argument and no second argument so it will slice off "ello world" without the "h".

Combine methods:
  • You can combine multiple methods to the same string. In the below example we will capitalize the first letter of "hello world".
  • Get the character at index 0, chain toUpperCase() to it, then concatenating the rest of the string from index 1. 
str; // returns "hello world"
str = str.charAt(0).toUpperCase() + str.slice(1);
str; // returns "Hello world"
  • Now Hello world has the first letter capitalized.

String.prototype.replace(regexpOrSubstr, newSubstr|function)
  • The replace method will replace the substring in the first argument with the string in the second argument. 
str = str.replace('world', 'planet'); // returns "hello planet"
str = str.replace(/planet/, 'world'); // returns "hello world"
  • The above example replaces "world" with "planet".
  • Instead of providing a substring you can use a regular expression. The second example above replaces "planet" back to "world".

String.prototype.repeat(count)
  • The repeat method will repeat the provided string the number of times provided in the argument. The below example adds 30 dashes across the screen.
view = '-'.repeat(30); // returns ------------------------------

Add strings together
  • To concatenate two or more strings together you can use the plus operator. The below example adds "hello" a space and "world".
str = 'Hello' + ' ' + 'World'; // returns "Hello World"

String.prototype.concat(string2[, string3, ..., stringN])
  • Or use the concat method. You'll get the same result.
str = 'Hello'.concat(' ', 'World');


4. Search/find methods

  • There are a number of methods for finding text in a string.
  • The below string contains the characters "cat" in some form four times. On its own in all lower case, on its own capitalized, and twice as part of other words.
str = 'This sentence contains the word cat. Cat is capitalized in this sentence, plus category and catch contain it.';

String.prototype.match(/regexp/)
  • The match method searches a string for a match against a regular expression and returns an array object with info about the first match.
view = str.match(/Cat/); // returns ['Cat', index: 37, input: 'This sentence contains the word cat. Cat is capitalized in this sentence, plus category and catch contain it.', groups: undefined]

  • The above example searches for a match on the letters "Cat" with C capitalized. Searches are case sensitive by default.
  • The result array contains the exact match characters, the index location of the match, and the search string content.

  • If there are multiple matches in the string, adding the global flag g will return an array of all the matches.
view = str.match(/Cat/ig); // returns ['cat', 'Cat', 'cat', 'cat']
    • Adding the "i" flag makes the search case insensitive. 
    • It returns an array of each match in the string. 

  • If you just want to get the total number of matches in the string, then chain the length property to the method. 
view = str.match(/Cat/ig).length; // returns 4

String.prototype.matchAll(/regexp/g)
  • If there are multiple matches and you want the full information on each match, you can use the below statements. This creates an array with the match info for reach match. Then iterates over the array logging the match info to the console.
const matches = [...str.matchAll(/Cat/ig)];
matches.forEach((match) => console.log(match)); // logs the array info for each match

String.prototype.indexOf(searchValue[, fromIndex])
  • The indexOf method will return the index position where the first occurrence of the string begins. The argument takes a string, not a regular expression. It returns -1 if there are no matches.
  • The below example searches for the index of the first occurrence of "cat". 
view = str.indexOf('cat'); // returns 32

String.prototype.lastIndex(searchValue[, fromIndex])
  • The lastIndex method does the same but gets the index of the last match.
view = str.lastIndexOf('cat'); // returns 92

String.prototype.search(/regexp/)
  • If you want to search for the index using a regular expression then use the search method. Regular expressions give you more flexibility in your search. 
  • The below example searches for Cat with C capitalized.
view = str.search(/Cat/); // returns 37

String.prototype.includes(searchString[, position])
  • If you just want a true or false result to your search, true if found, false if not, there are a few methods you can use.
  • Includes takes a search string as the argument, not a regular expression.
view = str.includes('category'); // returns true

String.prototype.startsWith(searchString[, position])
  • The startsWith method returns true if the string starts with the search string, otherwise false.
view = str.startsWith('This'); // returns true

String.prototype.endsWith(searchString[, position])
  • The endsWith method returns true if the string ends with the search string, otherwise false.
view = str.endsWith('not this'); // returns false
view = str.endsWith('it.');  // returns true


5. Compare Strings

  • You can compare strings with the standard comparison operators. They return true or false.

Examples:
let str = 'hello';
let view = (str === 'hello'); // returns true view = (str !== 'Hello'); // returns true. The comparison is case sensitive view = (str !== 'hello '); // returns true. Spaces are not ignored.

  • Strict equality === checks if the string value are exactly the same and are both string data types.
  • Strict inequality !== checks if the strings are NOT equal. 
  • You can use the greater than/less than comparison operators to compare strings. 
view = ('a' < 'z'); // returns true
  • Characters are compared by their unicode decimal number, which means that the upper case A-Z letters come before lower case a-z letters so they have lower unicode numbers.
view = ('a' > 'Z'); // returns true


6. Convert Data Types to/from String

  • There may be times where you want to convert data from other data types to a string.
  • There are two common ways to do this:
    • Call the String function in a non-constructor context (i.e., without the new operator). Pass in the value to convert as the argument.
    • Alternatively, chain the toString() instance method to the value. You can't chain it directly to a number so put parentheses around a number to make it an expression.
let str = String(7); // returns '7'
str = (7).toString(); // returns '7' str = String(true); // returns 'true' str = false.toString(); // returns 'false'

  • Using the String function or toString method on an object just returns "[object Object]".
str = String({ name: 'Joey', age: 32 }); // returns [object Object]
str = { name: 'Joey', age: 32 }.toString(); // returns [object Object]

  • Calling the String function or toString method on an array will put all the values into a string, with each item separated by a comma. 
str = String(['Joey', 'Sheena', 'Johnny']); // returns Joey,Sheena,Johnny
str = ['Joey', 'Sheena', 'Johnny'].toString(); // returns Joey,Sheena,Johnny

String.prototype.split([separator[, limit]])
  • The split method converts a string to an array. Pass in the separator character or characters as the argument and it will split the string into array items based on that separator.
let str = 'Joey, Sheena, Johnny,Judy';
let arr = str.split(', '); // returns ['Joey', 'Sheena', 'Johnny,Judy']

  • In the above example, the str variable is set to a string of names separated by commas.
  • The split method passes in a comma and space as the separator.
  • This splits the string into an array of 3 items. Two names were only separated by a comma with no space, so they were not split.

  • You can use a regular expression as the separator. 
let str = 'Joey, Sheena, Johnny,Judy';
arr = str.split(/, ?/); // returns ['Joey', 'Sheena', 'Johnny', 'Judy']

  • The above regular expression separates on a comma. Then there is a space followed by a question mark. That means if there is a space after the comma it will add that to the separator. If not it will just separate on the comma.
  • This returns an array with the string split into four items.

String.prototype.join([separator])
  • The join method does the opposite of the split method. It converts an array into a string. By default it will join all the items into one string, with each item separated by a comma. You can pass in a different separator as the argument.
arr; // returns  ['Joey', 'Sheena', 'Johnny', 'Judy']
str = arr.join(' | '); // returns "Joey | Sheena | Johnny | Judy"

  • The above example converts the array back into a string. It uses " | " as the separator.

Convert strings to numbers:
  • To convert string digits to numbers, call the Number function in a non-constructor context. Pass in the string as the argument.
let num = Number('7'); // returns 7
num = Number('19.95'); // returns 19.95

  • That concludes this tutorial on JavaScript Strings.


Conclusion

The topics in this tutorial correspond with the JavaScript CheatSheet Strings category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.

If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.
Open CheatSheet Back To List Next Tutorial