JavaScript String Methods
JavaScript string methods are essential for manipulating and processing text in web development. Whether you’re formatting user input, searching within text, or transforming strings, these methods offer a wide range of functionality. From basic operations like finding substrings with indexOf() and includes() to transforming text with toUpperCase(), replace(), split()and many more , understanding these methods will help you work more efficiently with strings in your code.
Table of Contents
- String Methods
Basic String Methods
charAt()charCodeAt()concat()includes()endsWith()startsWith()indexOf()lastIndexOf()slice()substring()toLowerCase()toUpperCase()trim()trimStart()trimEnd()
Intermediate String Methods
split()replace()replaceAll()repeat()padStart()padEnd()
Advanced String Methods
match()search()fromCharCode()codePointAt()
Let’s begin our Journey
1. charAt() & charCodeAt()
The charAt() method returns the character at a specified index in a string. & charCodeAt() method returns the Unicode value of the character at a specified index in a string.
Syntax: str.charAt(index)
// Example:
const greeting = "Hello World!";
const char = greeting.charAt(7);
console.log(char); // Output: 'W' (NOTE : It counts space also)
---------------------------------------------------------------------------
Syntax: str.charCodeAt(index)
// Example:
const greeting = "Hello World!";
const charCode = greeting.charCodeAt(7);
console.log(charCode); // Output: 87Note: The charCodeAt() method returns the Unicode (ASCII) value of a character. To view a complete list of ASCII values, you can visit the link for reference.
2. concat()
The concat() method merges two or more strings and returns a new concatenated string.
Syntax: str.concat(string2, string3, ..., stringN)
// Example:
const str1 = "Hello";
const str2 = "World";
const result = str1.concat(" ", str2, "!");
console.log(result); // Output: 'Hello World!'3. includes()
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax: str.includes(searchString, position)
// Example:
const sentence = "The brown fox jumps from the tree.";
const hasFox = sentence.includes("fox");
console.log(hasFox); // Output: true
const hasCat = sentence.includes("cat");
console.log(hasCat); // Output: falseGet ΛK⚡HΛY’s stories in your inbox
Join Medium for free to get updates from this writer.
4. endsWith() & startsWith()
The endsWith() method returns true or false depending on if a string ends with the characters from a provided string. & The startsWith() method returns true or false based on whether a string starts with the characters of a provided string.
Syntax: str.endsWith(searchString, length)
// Example:
const filename = "document.pdf";
const isPDF = filename.endsWith(".pdf");
console.log(isPDF); // Output: true
const isWord = filename.endsWith(".docx");
console.log(isWord); // Output: false
---------------------------------------------------------------------------
Syntax: str.startsWith(searchString, position)
// Example:
const message = "Hello, World!";
const startsWithHello = message.startsWith("Hello");
console.log(startsWithHello); // Output: true
const startsWithWorld = message.startsWith("World", 7);
console.log(startsWithWorld); // Output: true5. indexOf() & lastIndexOf()
The indexOf() method returns the index within the calling string of the first occurrence of the specified value. Returns -1 if the value is not found. & lastIndexOf() method returns the index within the calling string of the last occurrence of the specified value. Returns -1 if the value is not found.
Syntax: str.indexOf(searchValue, fromIndex)
// Example:
const phrase = "Find the needle in the box.";
const firstIndex = phrase.indexOf("needle");
console.log(firstIndex); // Output: 9
const notFound = phrase.indexOf("pin");
console.log(notFound); // Output: -1
---------------------------------------------------------------------------
Syntax: str.lastIndexOf(searchValue, fromIndex)
// Example:
const phrase = "Look for the last occurrence of the word 'the'.";
const lastIndex = phrase.lastIndexOf("the");
console.log(lastIndex); // Output: 42
const notFound = phrase.lastIndexOf("hello");
console.log(notFound); // Output: -16. slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
Syntax: str.slice(beginIndex, endIndex)
// Example:
const text = "JavaScript is awesome";
const slicedText = text.slice(0, 10);
console.log(slicedText); // Output: 'JavaScript'
const negativeSlice = text.slice(-7);
console.log(negativeSlice); // Output: 'awesome!'7. substring()
The substring() method returns the part of the string between the start and end indexes, or to the end of the string.
Syntax: str.substring(indexStart, indexEnd)
// Example:
const phrase = "Extract a substring from this string.";
const sub = phrase.substring(8, 16);
console.log(sub); // Output: 'substring'
const singleIndex = phrase.substring(8);
console.log(singleIndex); // Output: 'substring from this string.'8 . toLowerCase() & toUpperCase()
The toLowerCase() method returns the calling string value converted to lowercase. & toUpperCase() method returns the calling string value converted to uppercase.
Syntax: str.toLowerCase()
// Example:
const mixedCase = "Hello WORLD!";
const lowerCase = mixedCase.toLowerCase();
console.log(lowerCase); // Output: 'hello world!'
---------------------------------------------------------------------------
Syntax: str.toUpperCase()
// Example:
const mixedCase = "Hello world!";
const upperCase = mixedCase.toUpperCase();
console.log(upperCase); // Output: 'HELLO WORLD!'9. trim() & trimStart() & trimEnd()
The trim() method removes whitespace from both ends of a string. Whitespace includes spaces, tabs, and newline characters. & trimStart() method removes whitespace from the beginning of a string, similarly trimEnd() method removes whitespace from the end of a string.
Syntax: str.trim()
// Example:
const messyString = " ΛK⚡HΛY ";
const cleanString = messyString.trim();
console.log(cleanString); // Output: 'ΛK⚡HΛY'
---------------------------------------------------------------------------
Syntax: str.trimStart()
// Example:
const messyString = " ΛK⚡HΛY";
const cleanStart = messyString.trimStart();
console.log(cleanStart); // Output: 'ΛK⚡HΛY'
---------------------------------------------------------------------------
Syntax: str.trimEnd()
// Example:
const messyString = "ΛK⚡HΛY ";
const cleanEnd = messyString.trimEnd();
console.log(cleanEnd); // Output: 'ΛK⚡HΛY'Let’s continue our journey with Intermediate String Methods
1. split()
The split() method divides a string into an array of substrings, using a specified separator to determine where to make each split. It can also limit the number of splits.
Syntax: str.split(separator, limit)
=> separator (optional): Specifies where to divide the string.If an empty
string is used, the string will be split into individual characters.
=> limit (optional): Specifies the maximum number of splits.
// Example 1: Splitting a Sentence into Words
const sentence = "JavaScript is fun";
const words = sentence.split(" ");
console.log(words); // Output: ['JavaScript', 'is', 'fun']
// Example 2: Splitting by a Character
const date = "2024-10-10";
const parts = date.split("-");
console.log(parts); // Output: ['2024', '10', '10']
// Example 3: Splitting into Characters
const word = "Hello";
const characters = word.split("");
console.log(characters); // Output: ['H', 'e', 'l', 'l', 'o']2. replace() & replaceAll()
The replace() method replace a existing string into a new string. It only replaces the first occurrence. & replaceAll() replace all the string.
Syntax: str.replace(searchValue, newValue)
// Example 1: Replacing a Substring
const message = "Hello World!";
const newMessage = message.replace("World", "JavaScript");
console.log(newMessage); // Output: 'Hello JavaScript!'
---------------------------------------------------------------------------
Syntax: str.replaceAll(searchValue, newValue)
// Example 1: Replacing All Occurrences of a Substring
const text = "apple, banana, apple, apple";
const newText = text.replaceAll("apple", "orange");
console.log(newText); // Output: 'orange, banana, orange, orange'3. repeat()
The repeat() method returns a new string that contains the specified number of copies of the original string.
Syntax: str.repeat(count)
=> count: The number of times to repeat the string.
// Example 1: Repeating a Word
const word = "Hello!";
const repeatedWord = word.repeat(3);
console.log(repeatedWord); // Output: 'Hello!Hello!Hello!'4. padStart() & padEnd()
The padStart() method pads the string with another string (multiple times, if needed) until the string reaches the specified length. The padding is applied from the start (left) of the string, similarly if you want to add some string at the end it can be done using padEnd() method.
Syntax: str.padStart(targetLength, padString)
=> targetLength: The desired length of the resulting string.
=> padString : Provide the string to pad with at start.
// Example 1: Padding with Zeros
const number = "5";
const paddedNumber = number.padStart(3, "0");
console.log(paddedNumber); // Output: '005'
// Example 2: Padding with Characters
const name = "John";
const paddedName = name.padStart(10, "*");
console.log(paddedName); // Output: '******John'
--------------------------------------------------------------------------
Syntax: str.padEnd(targetLength, padString)
// Example 1: Padding for Formatting
const name = "John";
const paddedName = name.padEnd(10, ".");
console.log(paddedName); // Output: 'John......'
// Example 2: Padding a String to Align Columns
const item = "Apple";
const paddedItem = item.padEnd(10, " ");
const price = "$1.00";
console.log(`${paddedItem} ${price}`); // Output: 'Apple $1.00'Now, let’s dive into Advanced String Methods
1. match()
The match() method retrieves a string from the given data. It returns an array of matched results or null if no matches are found. If the regex has the global (g) flag, it returns all matches; otherwise, it returns only the first match.
Syntax: str.match(regexp)
=> regexp: A regular expression object.
Can be created using a regex literal or the RegExp constructor.
// Example 1: Finding a Single Match
const text = "There is a rain in amd city";
const result = text.match(/rain/);
console.log(result); // Output: ['rain']
// Example 2: Using a Global Regular Expression
const text = "Hello my name is akshay Hello nice to meet you Hello!";
const result = text.match(/Hello/g);
console.log(result); // Output: ['Hello', 'Hello', 'Hello']2. search()
The search() method tests a string for a match against a regular expression and returns the index of the first match. If no match is found, it returns -1.
Syntax: str.search(regexp)
// Example 1: Finding the Index of a Match
const text = "Hello World!";
const index = text.search(/World/);
console.log(index); // Output: 6
// Example 2: No Match Found
const text = "JavaScript is awesome";
const index = text.search(/Python/);
console.log(index); // Output: -13. String.fromCharCode()
The String.fromCharCode() method returns a string created from the sequence of Unicode values. It is used to generate characters based on their Unicode values.
Syntax: String.fromCharCode(num1, num2, ..., numN)One or more Unicode values.
// Example 1: Generating a Character
const char = String.fromCharCode(65); // 'A'
console.log(char); // Output: 'A'
// Example 2: Creating a String from Multiple Codes
const str = String.fromCharCode(72, 101, 108, 108, 111);
console.log(str); // Output: 'Hello'4. codePointAt()
The codePointAt() method returns a integer that is Unicode code value of that character at the given index in a string. It handles characters outside the Basic Multilingual Plane (BMP) correctly.
Syntax: str.codePointAt(index)
=> index: The position of the character whose value you want to get.
// Example 1: Getting the Code Point of a Character
const str = "A";
const codePoint = str.codePointAt(0);
console.log(codePoint); // Output: 65 (Unicode value for 'A')
// Example 2: Handling Emojis
const str = "😀";
const codePoint = str.codePointAt(0);
console.log(codePoint); // Output: 128512In this blog, we’ve covered a wide range of JavaScript string methods, from basic to advanced, to help you modify and work with text effectively in your projects. Understanding these methods can help you to improve your coding skills and handle strings . If you have any questions or insights, please share them in the comments section below. Happy coding!
2. Array methods
If you’re interested in diving deeper into JavaScript Array methods, I recommend checking out this comprehensive guide on Medium: JavaScript Array Methods. It provides detailed explanations and examples to help you master Array manipulation in JavaScript. Happy learning!










