JavaScript is one of the most used programming languages, which enables us to build cross-platform apps. You as a developer, interact with javascript to write code that empowers your app. Most of the time we are stuck badly with requirements and we need a quick solution, string manipulation is one of them.
In this article, I’m going to share some very useful JavaScript string manipulation techniques. These string methods help you write code faster.
Wants to increase the productivity as developer? Here is a list of the Best Handpicked dev tools for developers to increase their productivity.
This article has two parts.
- The first Part lists javascript core methods for string manipulation.
- The second part lists custom functions for manipulating strings.
Strings are one of the most commonly used data types, and controlling them efficiently can help you create dynamic, interactive web applications.
1) Convert to Uppercase & Lowercase
You can easily convert string to all uppercase & lowercase letters using the [.uppercase()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)
, and [.toLowerCase()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase)
method.
const str = "This is a string";
str.toUpperCase(); // OUTPUT: THIS IS A STRING
str.toLowerCase(); // OUTPUT: this is a string
2) Extract a Substring with substring()
The [.substring()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring)
javascript method extracts characters between two given indices (positions in the string, like array index).
const str = "JavaScript";
const subStr = str.substring(0, 4);
console.log(subStr); // "Java"
3) Extract a Substring with substr()
Another method, [.substr()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)
, extracts a part of the string based on a start position and a specific length.
const str = "JavaScript";
const result = str.substr(1, 4);
console.log(result); // "avaS"
The difference between substr()
and substring()
is that substr()
requires a starting index and a length, while substring()
uses start and end indices.
4) Slice a string
The [.slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
method is similar to substring()
, but it can also accept negative values to count from the end of the string.
const str = "JavaScript";
const slicedStr = str.slice(1, 4);
console.log(slicedStr); // "ava"
If you use a negative number, like str.slice(-3)
, it will return the last three characters from the string.
5) Split a String
The [.split()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
method divides a string into an array of substrings, based on a delimiter (a character or string that marks where to split).
This method is extremely useful when you want to break a string into individual words or elements, such as processing CSV data.
const str = "apple,banana,cherry";
const arr = str.split(",");
console.log(arr); // ["apple", "banana", "cherry"]
6) Replace a Substring
The [.replace()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
method lets you replace the first occurrence of a substring with something else.
const str = "Hello world";
const newStr = str.replace("world", "JavaScript");
console.log(newStr); // "Hello JavaScript"
7) Replace All Occurrences
The [.replaceAll()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll)
method replaces every occurrence of a substring.
const str = "Hello world world";
const newStr = str.replaceAll("world", "JavaScript");
console.log(newStr); // "Hello JavaScript JavaScript"
8) Trim Whitespace
The [.trim()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim)
method removes any whitespace (spaces, tabs, etc.) from both the beginning and the end of a string.
This is useful when you want to clean up user input or handle string formatting issues.
const str = " Hello World ";
const trimmedStr = str.trim();
console.log(trimmedStr); // "Hello World"
9) Remove Leading or Trailing Whitespace
You can also remove whitespace from only one side of the string using [.trimStart()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimStart)
or [.trimEnd()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trimEnd)
.
const str = " Hello World ";
console.log(str.trimStart()); // "Hello World "
console.log(str.trimEnd()); // " Hello World"
10) Get Character at a Specific Index
The [.charAt()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt)
method returns the character at a specified index.
const str = "JavaScript";
console.log(str.charAt(3)); // "a"
You can also use bracket notation, like str[3]
, to achieve the same result.
11) Get the Unicode Value of the Character
The [.charCodeAt()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt)
method returns the Unicode value of the character at a specific index.
This is helpful when you need to work with the underlying character codes (ASCII/Unicode).
const str = "JavaScript";
console.log(str.charCodeAt(0)); // 74 (for "J")
12) Search inside the String
The [.includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes)
method checks if a string contains a specific sequence of characters.
const str = "Hello JavaScript";
console.log(str.includes("JavaScript")); // true
13) Find the Index of a Substring
The [.indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
method returns the first occurrence of a substring, and [.lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf)
returns the last occurrence.
const str = "Hello world";
console.log(str.indexOf("o")); // 4
console.log(str.lastIndexOf("o")); // 7
14) Check if String Starts or Ends with a Substring
You can use [.startsWith()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith)
and [.endsWith()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith)
to check if a string starts or ends with a specific substring.
These methods are useful for validating string formats (e.g, checking if a URL starts with “http”).
const str = "JavaScript";
console.log(str.startsWith("Java")); // true
console.log(str.endsWith("Script")); // true
15) Repeat a String
The [.repeat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat)
method repeats a string a specified number of times.
const str = "Hello";
console.log(str.repeat(3)); // "HelloHelloHello"
16) Pad a String
You can add padding to the start or end of a string using [.padStart()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)
and [.padEnd()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd)
.
const str = "5";
console.log(str.padStart(3, "0")); // "005"
console.log(str.padEnd(3, "0")); // "500"
17) Using Template Literals
Template literals, introduced in ES6, are a modern way to work with strings in JavaScript.
They allow you to create multi-line strings, embed variables, and perform string interpolation in a more readable and convenient way.
const a = 10;
const b = 20;
console.log(`The sum of a and b is ${a + b}`); // "The sum of a and b is 30"
18) Formatting Currency Using .toLocaleString()
JavaScript’s [.toLocaleString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)
method allows you to format numbers as strings with appropriate formatting for different locales, including currency formatting.
This is especially useful when you want to display prices or financial data in a user-friendly way.
const amount = 2500;
// Format as US Dollar currency
const formattedUSD = amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
console.log(formattedUSD); // "$2,500.00"
// Format as Euro currency
const formattedEUR = amount.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
console.log(formattedEUR); // "2.500,00 €"
In part 2, I'll share some useful custom functions that help achieve some extra string manipulation, which is not possible with core JavaScript.
Thanks for reading. Stay in touch to get notifications of the next published article.
Top comments (0)