JavaScript String Properties & Methods

Home » JavaScript Tutorial » JavaScript Built-in Objects & Methods » JavaScript String Properties & Methods

JavaScript strings are primitive values. However, through the mechanism of temporary wrapper objects (Auto-Boxing), they provide access to a comprehensive suite of built-in properties and methods used for text manipulation and inspection. This lesson covers the most frequently utilized identifiers in the string prototype.

To view a complete inventory of every method available on the String prototype, the following command can be executed in the browser console. This outputs an array of all available built-in property names for strings.

console.log(Object.getOwnPropertyNames(String.prototype));

// Output: (52) ['length', 'constructor', 'anchor', 'at', 'big', 'blink', 'bold', 'charAt', 'charCodeAt', 'codePointAt', 'concat', 'endsWith', 'fontcolor', 'fontsize', 'fixed', 'includes', 'indexOf', 'isWellFormed', 'italics', 'lastIndexOf', 'link', 'localeCompare', 'match', 'matchAll', 'normalize', 'padEnd', 'padStart', 'repeat', 'replace', 'replaceAll', 'search', 'slice', 'small', 'split', 'strike', 'sub', 'substr', 'substring', 'sup', 'startsWith', 'toString', 'toWellFormed', 'trim', 'trimStart', 'trimLeft', 'trimEnd', 'trimRight', 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'valueOf']
JavaScript

1. String Properties: Properties represent stored data regarding the string instance. They are accessed directly via dot notation without parentheses.

  • .length: Returns a number representing the total count of characters in the string, including whitespace and special characters.
const getLength = "String";
console.log(getLength.length); // Output: 6 (number of characters)
JavaScript

2. String Methods: Methods are functions associated with the string. They perform actions, such as searching, slicing, or formatting, and must be invoked with parentheses ().

  • .toUpperCase() / .toLowerCase(): Returns a new string with all characters converted to upper or lower case, respectively.
  • .includes(substring): Performs a case-sensitive search to determine if one string may be found within another. Returns a Boolean (true or false).
  • .slice(start, end): Extracts a section of a string and returns it as a new string, without modifying the original string.
const myString = "String";
console.log(myString.toUpperCase()); // Output: STRING

const includesCheck = "String";
console.log(includesCheck.includes("t")); // Output: true

const sliceString = "String";
console.log(sliceString.slice(2,6)); // Output: ring
JavaScript

Strings in JavaScript are immutable, just like other primitive data-types (i.e numbers, booleans) that are not the object type which includes arrays. This means that string methods do not change the original string variable. Instead, they generate and return a new string containing the modified data. To persist changes, the result must be assigned to a new variable or reassigned to the existing one.

// Immutability Example:
let greeting = "Hello World";
greeting.replace("World", "Universe"); 
console.log(greeting); 
// Output: "Hello World" (Original is unchanged)

// Instead we need assign the result/value to a new variable:
const newGreeting = greeting.replace("World", "Universe");
console.log(newGreeting); 
// Output: "Hello Universe"
JavaScript

1. Transformation and Case Conversion: These methods modify the case or spacing of the string.

// Transformation and Case Conversion:
const username = "  [email protected]  ";
const sentenceToFix = "I love red and blue.";

// .trim(): Removes whitespace from both ends of the string.
const trimmedUser = username.trim();
console.log(trimmedUser); // Output: [email protected]

// .toUpperCase(): Converts the entire string to uppercase.
console.log(trimmedUser.toUpperCase()); // Output: [email protected]

// .toLowerCase(): Converts the entire string to lowercase.
console.log(trimmedUser.toLowerCase()); // Output: [email protected]

// .replace(): Replaces the FIRST occurrence of a match.
console.log(sentenceToFix.replace("red", "green")); // Output: I love green and blue.

// .replaceAll(): Replaces ALL occurrences of a match.
const colors = "Red, Blue, Red, Green";
console.log(colors.replaceAll("Red", "Yellow")); // Output: Yellow, Blue, Yellow, Green
JavaScript

2. Searching and Inspection: These methods check the content of the string and return a Boolean or an index.

// Searching and Inspection:
const sentence = "The quick brown fox jumps over the lazy dog.";
const target = "fox";

// .length: Returns the total number of characters (a property, not a method).
console.log(sentence.length); // Output: 44

// .includes(): Checks if the string contains a substring (returns true/false).
console.log(sentence.includes(target)); // Output: true ('fox' is present)

// .indexOf(): Returns the starting index (position) of the first match. Returns -1 if not found.
console.log(sentence.indexOf(target)); // Output: 16 (The 'f' is at index 16)

// .startsWith(): Checks if the string begins with the specified text.
console.log(sentence.startsWith("The")); // Output: true

// .endsWith(): Checks if the string ends with the specified text.
console.log(sentence.endsWith("dog.")); // Output: true
JavaScript

3. Extraction, Slicing, and Padding: These methods extract a portion of the string or add characters for formatting.

// Extraction, Slicing, and Padding:
const data = "USER_ID_789_ACTIVE";
const dateNum = "5";

// .slice(start, end?): Extracts a section of the string. End index is exclusive.
console.log("The quick brown fox".slice(4, 9)); // Output: quick

// .substring(start, end?): Similar to slice, but cannot accept negative arguments.
console.log(data.substring(8, 12)); // Output: 789_
// "end?" means the second parameter is optional in .substring
console.log(data.substring(11)); // Output: _ACTIVE (index 11 to the last index)

// .at(index): Returns the character at a specific index with a negative value.
console.log(data.at(-2)); // Output: V (counts down from end)

// .charAt(index): Returns the character at an index (doesn't accept negative indexes).
console.log(data.charAt(1)); // Output: S

// .padStart(targetLength, padString): Adds padding to the START.
// Ensure numbers always 4 characters long, padding with '0' in front of number.
console.log(dateNum.padStart(4, "0")); // Output: 0005 (originally '5')

// .padEnd(targetLength, padString): Adds padding to the END.
const paddedName = "1234".padEnd(16, "*");
console.log(paddedName); // Output: 1234************
JavaScript

4. Conversion, Regular Expressions, and Utility: These methods perform complex transformations or are used with advanced language features.

// Conversion, Regular Expressions, and Utility:
const csvData = "apple banana cherry date";
const phrase = "Wow! ";

// .split(separator): Converts the string into an array of substrings.
const fruitArray = csvData.split(" ");
console.log(fruitArray); // Output: [ 'apple', 'banana', 'cherry', 'date' ]

// .repeat(count): Creates a new string by repeating the original.
console.log(phrase.repeat(3)); // Output: Wow! Wow! Wow!

// .concat(): Joins strings together (usually simpler with the + operator).
console.log("Hello".concat(", ", "World!")); // Output: Hello, World

// .match(regexp): Searches for a match against a Regular Expression (advanced).
// (Example requires knowledge of RegExp)
// "\d" means digit, "+" means 1 or more (find a sequence with 1 or more digits).
console.log("Invoice 2025".match(/\d+/)); // Output: ['2025', index: 8, input: 'Invoice 2025', groups: undefined]

// .charCodeAt(index): Returns the Unicode value of the character at the specified index.
console.log("A".charCodeAt(0)); // Output: 65
JavaScript

While this overview covers the most common methods, you can refer to the String prototype object in your console for a complete inventory of every method available for further experimentation.