๐งต Strings Cheat Sheet
Introduction
A cheat sheet you can bookmark for most of the JavaScript string methods. ๐ฅ
Here is a quick reference of the most common ones before we go into detail:
| Method | What it does | Returns |
|---|---|---|
| .split(sep) | Splits a string by a separator | string[] |
| .includes(str) | Checks if a substring exists | boolean |
| .indexOf(str) | Finds the first position of a substring | number (-1 if not found) |
| .slice(start, end) | Extracts a section of the string | string |
| .replace(match, new) | Replaces the first match | string |
| .trim() | Removes whitespace from both ends | string |
| .toLowerCase() | Converts all characters to lower case | string |
| .startsWith(str) | Checks if the string begins with a value | boolean |
| .padStart(len, fill) | Pads the start until it reaches the target length | string |
| .repeat(count) | Repeats the string n times | string |
Before we jump in, a quick reminder on primitive types. JavaScript will automatically convert a primitive string (one defined with quotes) to a string object, making it possible to use JavaScript string object methods that can manipulate the sequence of characters. For example:
1let primitiveString = 'Primitive';2let stringObject = new String(primitiveString);34console.log(typeof primitiveString) // "string"5console.log(typeof stringObject) // "object"67/*8This is what the object will look like:9 String {"Primitive"}10 0: "P"11 1: "r"12 2: "i"13 3: "m"14 4: "i"15 5: "t"16 6: "i"17 7: "v"18 8: "e"1920To convert back to primitive type use "valueOf()" method.21stringObject.valueOf(); --> "Primitive"22*/
Quick Find:
- Find String in String
- .indexOf();
- .lastIndexOf();
- Get String Parts
- .slice();
- .substring();
- .substr();
- Replace Content
- .replace();
- Transform Characters (Upper & Lower)
- .toLowerCase();
- .toUpperCase();
- Concat
- .concat();
- Template Literals `${someVal} text ${anotherVal}`;
- Trim String
- .trim();
- Extracting Characters
- .charAt();
- .charCodeAt();
- String to Array
- .split();
String Methods & Properties
String Length
Property: .length
Description: Property to return string length.
1const string = 'The Joe Codes';2const length = string.length;3console.log(length) // 13
Find a String in String
Method: .indexOf()
Description: Method to return position of first occurrence of string in string.
First Parameter:
- The Search value
- Required
- A string to search for.
Second Parameter:
- Start position
- Optional (defaults to 0)
- Position to start the search.
1const string = 'The Joe Codes';2const position = string.indexOf('Joe');3console.log(position); // 4
Method: .lastIndexOf()
Description: Method to return position of last occurrence of string in string.
First Parameter:
- The Search value
- Required
- A string to search for.
Second Parameter:
- Start position
- Position to start the search, searches backwards.
- Optional (defaults to length of string)
1const string = 'The Joe Codes, The Joe Codes';2const position = string.lastIndexOf('Joe');3console.log(position); // 19
- Both methods take a second parameter used for the search starting position.
- Both methods return -1 when no string is found.
- Both methods are case sensitive, consider using .toLowerCase() first.
1const string = 'The Joe Codes, The Joe Codes';23// Searches backwards from position 18 to start of string4const position = string.lastIndexOf('Joe', 18);56console.log(position); // 478// index & lastIndexOf are CasE SenSItiVE !!9const positionTwo = string.lastIndexOf('joe', 18);1011// index & lastIndexOf will return -1 when no string is found12console.log(positionTwo); // -1
Getting String Parts
Method: .slice()
Description: Method to return extracted parts of string as a new string.
First Parameter:
- Start position
- Required
- The position to start extracting.
Second Parameter:
- End position
- Optional
- Position to end string extracting. Extracts up to the position but not including it. When omitted, slice function will extract all chars from the specified start position.
1const string = 'The Joe Codes';2const result = string.slice(3,6);3console.log(result); // Jo45// Visualised6const obj = new String('The Joe Codes');7console.log(obj);89/*10String {"The Joe Codes"}110: "T"121: "h"132: "e"143: " " <---154: "J" Extract me165: "o" Extract me176: "e" <---187: " "198: "C"209: "o"2110: "d"2211: "e"2312: "s"24length: 1325*/
If a parameter is negative, count -n from the end of the string. If you omit the second parameter, the method will slice out the rest of the string:
1const string = 'The Joe Codes';2// negative param, we start at end of the string and skip the last 's' in 'Codes'3const result = string.slice(3, -1);4console.log(result); // Joe Code56// only one paramater, slice out the rest of the string to the end7const result2 = string.slice(1);8console.log(result2); // he Joe Codes
Method: .substring()
Description: Method to return the extracted parts of a string as a new string. Similar to .slice() method, but cannot accept negative indexes.
First Parameter:
- Start position
- Required
- The position to start extracting.
Second Parameter:
- End position
- Optional
- Position to end string extracting. Extracts up to the position but not including it. When omitted, slice function will extract all chars from the specified start position.
Method: .substr()
Description: Method to return the extracted parts of a string as a new string. Similar to .slice() method, but the second paramter specifies the length of the extracted part.
First Parameter:
- Start position
- Required
- The position to start extracting. First char is at index 0.
Second Parameter:
- length
- Optional
- Number of characters used to extract (not the position!), starting from the start position. When omitted, slice function will extract all chars from the specified start position.
1const string = 'The Joe Codes';2const result = string.substr(0, 5);3console.log(result); // The J45// Visualised6const obj = new String('The Joe Codes');7const result2 = obj.substr(0, 5);8console.log(result2); // The J910/*11String {"The Joe Codes"}120: "T" <-- Start here & extract me (character count = 1, position = [0])131: "h" <-- Extract me (character count = 2, postion = [1])142: "e" <-- Extract me (character count = 3, postion = [2])153: " " <-- Extract me (character count = 4, postion = [3])164: "J" <-- Extract me (character count = 5, postion = [4]) STOP character count of '5' reached!175: "o" ... ignored from here186: "e"197: " "208: "C"219: "o"2210: "d"2311: "e"2412: "s"25length: 1326*/
Replacing String Content
Method: .replace()
Description: Method to replace string characters with another set of string characters.
First Parameter:
- The Search value
- Required
- A search string representing the value to replace. See first example below.
- A RegExp pattern can be used as the first parameter, as an object or literal. Regular expression matches will be replaced with the second string parameter, which can be a function return. See 'Regex Example' below.
- A function can be used, so long as it returns a string. See 'Function Example' below.
Second Parameter:
- The new value
- Required
- Can be a string value to replace search value with. See first example below.
- Can be a function, so long as it returns a string. The callback function provided will have access to matches. See 'Function With Regex Example' below.
1// * The replace method does not mutate the original string, it returns a new string2// * The replace method is CaSe SenSItiVe! Consider using .toLowerCase() first or regex34const string = 'The Joe Codes';5// Signature: .replace(stringToReplace, replaceWithThisString);6const result = string.replace('Joe Codes', 'JavaScript Strings Cheat Sheet');7console.log(result); // The JavaScript Strings Cheat Sheet8910/* Regex Example */1112// Global, case-insensitive regex to match 'joe codes'13const regex = /joe codes/gi;14// Signature: .replace(regex, replaceRegexMatchesWithThisString);15const regexResult = string.replace(regex, 'JavaScript Strings Cheat Sheet');16console.log(regexResult); // The JavaScript Strings Cheat Sheet171819/* Function Example */2021const toReplace = () => 'Joe Codes';22const replaceWith = () => 'JavaScript Strings Cheat Sheet';23const functionResult = string.replace(toReplace(), replaceWith());24console.log(regexResult); // The JavaScript Strings Cheat Sheet2526/* Function With Regex Example */2728const lowercaseString = "the joe codes";29// Replace 'the' or 'joe' globally and case insensitive30// Each regex match is passed into the function and replaced with an upper cased version31const regexFunctionResult = lowercaseString.replace(/the|joe/gi, (match) => match.toUpperCase());32console.log(regexFunctionResult); // THE JOE codes
Upper/Lower Case a String
Method: .toLowerCase()
Description: Method to convert all string characters to lower case.
Method: .toUpperCase()
Description: Method to convert all string characters to upper case.
1const string = 'The Joe Codes';2const lower = string.toLowerCase();3const upper = string.toUpperCase();4console.log(upper); // THE JOE CODES5console.log(lower); // the joe codes
Concat
Method: .concat()
Description: Method to join strings.
Parameters:
- The string(s)
- Required
- The string(s) to be joined to the original string concat is being called on.
1const string = 'The';2const stringTwo = 'Joe';3const stringThree = 'Codes';4// Remember, all string methods don't mutate the original string5// ... they return a new string6// Strings are immutable!7const result = string.concat(' ', stringTwo, ' ', stringThree);8console.log(result); // The Joe Codes910// ... Although, who even uses concat these days!?11const es6 = `${string} ${stringTwo} ${stringThree}`;12console.log(es6); // The Joe Codes
Trim String Whitespace
Method: .trim()
Description: Method to trim whitespace from either side of a string.
1const string = ' The Joe Codes ';2const result = string.trim();3console.log(result); // 'The Joe Codes'
Extracting Characters
Method: .charAt()
Description: Method to return char at index specified.
Method: .charCodeAt()
Description: Method to return char unicode (UTF-16 code) at index specified.
1const string = 'The Joe Codes';2console.log(string.charAt(0)); // 'T' (String)3console.log(string.charCodeAt(0)); // 84 (Integer)45// or via property access.. but looks strange!?6// I never use this one, kind of seems like array access7// ... I would avoid !8console.log(string[0]);
String to Array
Method: .split()
Description: Method to convert a string to an array data structure.
First parameter:
- The separator
- Optional. When omitted, entire string returned as a new array with one value.
- Regex or char used to split the string into an array.
Second parameter:
- The limit
- Optional
- Integer used to specify how many items can be split into an array / the size of the array.
1const string = 'The Joe Codes';2const result = string.split(' ');3const resultTwo = string.split('');4const resultThree = string.split('Joe');56console.log(result); // 'The Joe Codes'7/*8["The", "Joe", "Codes"]90: "The"101: "Joe"112: "Codes"12*/13console.log(resultTwo); // 'The Joe Codes'14/*15["T", "h", "e", " ", "J", "o", "e", " ", "C", "o", "d", "e", "s"]160: "T"171: "h"182: "e"193: " "204: "J"215: "o"226: "e"237: " "248: "C"259: "o"2610: "d"2711: "e"2812: "s"29*/30console.log(resultThree); // 'The Joe Codes'31/*32["The ", " Codes"]330: "The "341: " Codes"35*/
Final Thoughts
If you find yourself struggling to remember all the string methods or how to use them, make sure to bookmark this article for future reference. You can check out the full JavaScript string reference over on the MDN docs.
Was this useful?
Thanks for reading! Time for one more?
let val: unknown = getData()if (typeof val === 'string') {console.log(val.toUpperCase())}
๐ก๏ธ TS Basic Types
04 Feb 2021 โข ๐ 13 min read โข Updated 15 Mar 2026A light introduction into the world of TypeScript and basic data types.
const el = document.getElementById('app')renderLoader(el)const data = await fetchUsers()el.innerHTML = createHtml(data)
๐ฆ Vanilla JavaScript
13 Dec 2020 โข ๐ 10 min read โข Updated 15 Mar 2026Life without a modern JavaScript framework. Vanilla JS fun.