Skip to content

ES6 - Strings

In JavaScript, a string is a sequence of characters used to represent text. String primitives are immutable, meaning their content cannot be changed once created. The String object is a wrapper around the string primitive data type, providing many helpful methods for working with text.

JavaScript automatically converts between string primitives and String objects, so you can call String object methods directly on string literals or variables holding string primitives.

// String literal (preferred for primitives)
const greeting = "Hello, World!";
const name = 'Alice';
// Using the String constructor (less common for creating primitives)
// This creates a String object, not a primitive
const strObject = new String("I am an object");
console.log(typeof greeting); // "string"
console.log(typeof strObject); // "object"

The String object (and string primitives via auto-wrapping) have the following properties:

Sr.NoPropertyDescription
1constructorReturns a reference to the String function that created the instance’s prototype. Generally not used in everyday coding.
2lengthReturns the number of characters (UTF-16 code units) in the string.
const message = "JavaScript";
console.log(message.length); // Output: 10

Here is a list of commonly used methods available on string primitives and String objects. Note that string methods do not modify the original string; they return a new string.

Sr.NoMethodDescription
1charAt(index)Returns the character at the specified index.
2charCodeAt(index)Returns a number indicating the UTF-16 code unit value of the character at the given index.
3concat(str1, str2, ..., strN)Combines the text of one or more strings and returns a new string. (The + operator is often preferred for concatenation).
4includes(searchString, position?)ES6 Method: Determines whether one string may be found within another string, returning true or false. Optional position to start searching from.
5endsWith(searchString, length?)ES6 Method: Determines whether a string ends with the characters of a specified string, returning true or false. Optional length to consider as the end of the string.
6indexOf(searchValue, fromIndex?)Returns the index within the calling String object of the first occurrence of the specified searchValue, or -1 if not found. Optional fromIndex to start searching from.
7lastIndexOf(searchValue, fromIndex?)Returns the index within the calling String object of the last occurrence of the specified searchValue, searching backwards from fromIndex, or -1 if not found.
8localeCompare(compareString, locales?, options?)Returns a number indicating whether a reference string comes before, after, or is the same as the given string in sort order, sensitive to locale.
9match(regexp)Retrieves the result of matching a string against a regular expression.
10matchAll(regexp)ES2020 Method: Returns an iterator of all results matching a string against a regular expression, including capturing groups.
11padStart(targetLength, padString?)ES2017 Method: Pads the current string from the start with a given string (repeated, if necessary) so that the resulting string reaches a given length.
12padEnd(targetLength, padString?)ES2017 Method: Pads the current string from the end with a given string (repeated, if necessary) so that the resulting string reaches a given length.
13repeat(count)ES6 Method: Returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
14replace(searchValue, replacer)Returns a new string with some or all matches of a pattern replaced by a replacement. searchValue can be a string or a RegExp. replacer can be a string or a function.
15replaceAll(searchValue, replacer)ES2021 Method: Returns a new string with all matches of a pattern replaced by a replacement. searchValue can be a string or a RegExp (if global).
16search(regexp)Executes the search for a match between a regular expression and this String object. Returns the index of the first match, or -1.
17slice(beginIndex, endIndex?)Extracts a section of a string and returns it as a new string, without modifying the original string. endIndex is exclusive.
18split(separator?, limit?)Splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
19startsWith(searchString, position?)ES6 Method: Determines whether a string begins with the characters of a specified string, returning true or false. Optional position to start searching from.
20substring(indexStart, indexEnd?)Returns the part of the string between the start and end indexes, or to the end of the string. If indexStart is greater than indexEnd, arguments are swapped.
21toLowerCase()Returns the calling string value converted to lower case.
22toLocaleLowerCase(locales?)The characters within a string are converted to lower case while respecting the current or specified locale.
23toUpperCase()Returns the calling string value converted to upper case.
24toLocaleUpperCase(locales?)The characters within a string are converted to upper case while respecting the current or specified locale.
25trim()Removes whitespace from both ends of a string.
26trimStart() / trimLeft()ES2019 Method: Removes whitespace from the beginning of a string.
27trimEnd() / trimRight()ES2019 Method: Removes whitespace from the end of a string.
28valueOf()Returns the primitive value of a String object.

The substr(start, length) method is considered a legacy feature in ECMAScript and its use is discouraged. It might be removed in future versions. Use substring(start, end) or slice(start, end) instead.

const text = " Hello ES6 World! ";
console.log(`Original: '${text}'`);
console.log(`Length: ${text.length}`);
console.log(`charAt(3): ${text.charAt(3)}`); // 'e' (after trimming conceptually)
console.log(`includes('ES6'): ${text.includes('ES6')}`); // true
console.log(`indexOf('World'): ${text.indexOf('World')}`); // 11 (after trimming conceptually)
console.log(`slice(8, 11): '${text.trim().slice(6, 9)}'`); // 'ES6'
console.log(`toUpperCase(): '${text.toUpperCase()}'`);
console.log(`trim(): '${text.trim()}'`);
console.log(`split(' '):`, text.trim().split(' ')); // ["Hello", "ES6", "World!"]

For comprehensive details on all string methods, refer to the MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String