How to Manipulate Strings in JavaScript

This tutorial is first published at FreeCodeCamp.

String manipulation is a common task for programmers, whether it is extracting information from the string, converting letter cases, joining strings, or trimming extra white spaces.

This tutorial covers various methods and techniques for manipulating strings using JavaScript, offering you a comprehensive guide on how to work with strings in your JavaScript applications.

How to extract a character from string

Let's start by talking about how to extract a single character from a string. JavaScript offers three different methods for this purpose: charAt(), at(), and charCodeAt().

  • charAt(index)

The charAt() method accepts an index, and returns the character at that index.

javascript
const str = "Hello World!";
 
console.log(str.charAt(0));
console.log(str.charAt(8));
console.log(str.charAt(16));
text
H
r
 

If the index is out of range, charAt() will return an empty string ("").

  • at(index)

The at() method is added to JavaScript with ES2022, and it is very similar to charAt(). You pass it an index, and the method returns the character at that index.

javascript
const str = "Hello World!";
 
console.log(str.at(0));
console.log(str.at(8));
console.log(str.at(16));
text
H
r
undefined

When the index is out of range, at() will return undefined instead of an empty string.

Another difference is that at() allows for negative indexing, meaning index -1 returns the last character of the string, -2 returns the second last character, and so on.

javascript
const str = "Hello World!";
 
console.log(str.at(-1));
console.log(str.at(-2));
text
!
d

Before at(), the only way to do this is through the length property.

javascript
const str = "Hello World!";
 
console.log(str.charAt(str.length - 1)); // The last character
console.log(str.charAt(str.length - 2)); // The second last character
text
!
d
  • charCodeAt(index)

The charCodeAt() method returns the UTF-16 code of the character at the specified index.

javascript
const str = "Hello World!";
 
console.log(str.charCodeAt(0));
console.log(str.charCodeAt(4));
text
72
111

How to extract a substring

Besides extracting a single character, JavaScript also allows you to extract a substring using methods substring() and slice().

  • substring(start, end)

substring() extracts a substring based on the provided start (inclusive) and end (exclusive) indexes, and returns the substring as a new string.

javascript
const str = "JavaScript";
 
console.log(str.substring(0, 4));
text
Java

The end index can be left out, in which case the substring will extracted from start to the end of the string.

javascript
const str = "JavaScript";
 
console.log(str.substring(4));
text
Script
  • slice(start, end)

slice() is very similar to substring(). It also extracts a substring based on the provided start and end indexes, and returns the substring as a new string.

javascript
const str = "JavaScript";
 
console.log(str.slice(0, 4));
text
Java

The end index can also be omitted.

javascript
const str = "JavaScript";
 
console.log(str.slice(4));
text
Script

The difference is that slice() accepts negative indexes. For example, the following example extracts the substring from index -10 to -6.

javascript
const str = "JavaScript";
 
console.log(str.slice(-10, -6));
text
Java

How to convert string to upper and lower cases

The methods toUpperCase() and toLowerCase() converts the string to upper or lower cases.

javascript
const str = "JavaScript";
 
console.log(str.toUpperCase());
console.log(str.toLowerCase());
text
JAVASCRIPT
javascript

How to join two strings together

The easiest way to join two strings together is using the + operator:

javascript
const str1 = "Hello";
const str2 = "World!";
 
const str3 = str1 + " " + str2;
 
console.log(str3);
text
Hello World!

Alternatively, you can use the concat() method:

javascript
const str1 = "Hello";
const str2 = "World!";
 
const str3 = str1.concat(" ", str2);
 
console.log(str3);
text
Hello World!

Or the template literals:

javascript
const str1 = "Hello";
const str2 = "World!";
 
const str3 = `${str1} ${str2}`;
 
console.log(str3);
text
Hello World!

How to trim extra white spaces from string

When working with strings that came from external sources, such as parsed from a webpage or received from user input, a common problem you might encounter is the leading and trailing white spaces.

JavaScript offers three different methods that allow you to easily remove the extra white spaces and keep only the useful information.

The trimStart() method removes the leading white spaces, including spaces, tabs, and line breaks. The trimEnd() method removes trailing white spaces, and trim() removes white spaces from both ends.

javascript
const str = "  \n\tHello World!\t\n  ";
 
console.log(str.trimStart());
console.log(str.trimEnd());
console.log(str.trim());
text
Hello World!
 
 
  Hello World!
Hello World!

How to add padding to string

The methods padStart() and padEnd() can be used to pad characters or substrings to the beginning or the end of the original string.

Both methods take two arguments, length and a substring. The substring will be repeated multiple times, until the resulting string reaches the target length.

javascript
const str = "123";
 
console.log(str.padStart(5, "0"));
console.log(str.padEnd(5, "0"));
text
00123
12300

If the substring is causing the resulting string to exceed the target length, then only a part of that substring will be used.

javascript
const str = "123";
 
console.log(str.padStart(8, "ok"));
text
okoko123

Notice that the substring "ok" is repeated twice, but for the third time, it causes the resulting string to exceed the length limit, so only "o" is used for the final padding.

How to repeat a string

The repeat() returns a new string, with the specified number of copies of the original string.

javascript
const str = "123";
 
console.log(str.repeat(3));
text
123123123

How to split string into an array

The split() method splits the string based on the given character, and returns the result in an array. This method is most useful when you need to extract information from a URL. For example, this is how you can extract the slug of a blog post:

javascript
const url = "http://www.example.com/blog/example-article";
 
let arr = url.split("/");
console.log(arr);
 
let slug = arr[4];
console.log(slug);
text
[ 'http:', '', 'www.example.com', 'blog', 'example-article' ]
example-article

How to search in a string

You can also search for a character or substring using JavaScript.

  • indexOf() and lastIndexOf()

The indexOf() method returns the index of the first occurrence of the given character.

The lastIndexOf() methods returns the index of the last occurrence of the given character.

javascript
const str = "Hello World";
 
console.log(str.indexOf("l"));
console.log(str.lastIndexOf("l"));
text
2
9

Both methods will return -1 if a match is not found.

javascript
const str = "Hello World";
 
console.log(str.indexOf("x"));
console.log(str.lastIndexOf("x"));
text
-1
-1
  • includes()

The includes() method tests if the string contains the given character or substring. It returns true if the substring is found, otherwise false will be returned.

javascript
const str = "JavaScript";
 
console.log(str.includes("S"));
console.log(str.includes("Script"));
console.log(str.includes("script"));
text
true
true
false
  • startsWith() and endsWith()

As the name suggests, these two methods test if the given substring is found at the beginning or the end of the string.

javascript
const str = "JavaScript";
 
console.log(str.startsWith("Java"));
console.log(str.endsWith("Java"));
 
console.log(str.startsWith("Script"));
console.log(str.endsWith("Script"));
text
true
false
false
true

How to search in a string using Regex

However, what if you need something more powerful? For example, the indexOf() and lastIndexOf() methods only return the first and last occurrences of the substring, but what if you need to search for all of them?

Or what if, instead of a substring, you need to search for a pattern, such as a phone number or a price tag?

This can be achieved by combining the string methods with Regex, which stands for regular expression. It is a programming tool that allows you to describe patterns in a string. Regex has a very cryptic syntax, but can be very useful sometimes.

  • search()

The search() method works similarly to indexOf() we just discussed. It also returns the first occurrence of the matched substring or pattern, except that search() allows you to pass a regular expression.

The following example, /(?<=\$)\d\d?\d?\d?/, searches for a price tag in the string, which should start with a dollar sign ($), and followed by 1 to 4 numeric digits.

javascript
const str = "The laptop costs $1500. The tablet costs $1000.";
 
console.log(str.search("1500"));
console.log(str.search(/(?<=\$)\d\d?\d?\d?/));
console.log(str.search(/(?<=\$)\d\d?\d?\d?/g));
text
18
18
18

Notice that the global flag (g) has no effect on search(), and it still returns the first occurrence of the match.

  • match() and matchAll()

Compared to search(), the match() method returns much more information that you can work with, such as the actual substring that matches the pattern, the index where the match is found, and more.

javascript
const str = "The laptop costs $1500. The tablet costs $1000.";
 
console.log(str.match(/(?<=\$)\d\d?\d?\d?/));
console.log(str.match(/(?<=\$)\d\d?\d?\d?/g));
text
[
 '1500',
 index: 18,
 input: 'The laptop costs $1500. The tablet costs $1000.',
 groups: undefined
]
[ '1500', '1000' ]

By including a global flag, you can make match() return all matched substrings, instead of just the first one.

There is also a matchAll() method that forces you to use the global flag. Without it, the method will return a TypeError.

matchAll() will return a iterable object, which you can iterate over using a for of loop.

javascript
const str = "This laptop costs $1500. The tablet costs $1000.";
 
const prices = str.matchAll(/(?<=\$)\d\d\d\d/g);
 
for (let price of prices) {
  console.log(price);
}
text
[
 '1500',
 index: 19,
 input: 'This laptop costs $1500. The tablet costs $1000.',
 groups: undefined
]
[
 '1000',
 index: 43,
 input: 'This laptop costs $1500. The tablet costs $1000.',
 groups: undefined
]

How to replace a string pattern

Lastly, the replace() method allows you to match for a pattern, and then replace the matched substrings with a new string. For example,

javascript
const str = "JavaScript javaScript Javascript";
 
console.log(str.replace(/JAVASCRIPT/i, "javascript"));
console.log(str.replace(/JAVASCRIPT/gi, "javascript"));
text
javascript javaScript Javascript
javascript javascript javascript

By default, replace() only matches and replaces the first occurrence of the pattern, but with the global flag, you can replace all matched patterns.

Conclusion

In this tutorial, we explored various methods you can use to work with strings in JavaScript, and also covered how to use regular expressions to match for string patterns.

As a brief summary, here are the methods we discussed in this tutorial:

  • charAt(index): Extracts the character at the specified index from a string.
  • at(index): Retrieves the character at the specified index, supports negative indexing.
  • charCodeAt(index): Returns the UTF-16 code of the character at the specified index.
  • substring(start, end): Extracts a part of the string between the start (inclusive) and end indexes (exclusive).
  • slice(start, end): Similar to substring(), extracts a part of the string between start (inclusive) and end indexes (exclusive), but supports negative indexing.
  • toUpperCase(): Converts all letters in the string to uppercase.
  • toLowerCase(): Converts all letters in the string to lowercase.
  • concat(): Joins two or more strings together.
  • trimStart(): Removes whitespace from the beginning of a string. Including spaces, tabs, and newlines.
  • trimEnd(): Removes whitespace from the end of a string.
  • trim(): Removes whitespace from both ends of a string.
  • padStart(length, substring): Pads the start of a string with another string (multiple times, if needed) until the resulting string reaches the given length.
  • padEnd(length, substring): Pads the end of the string with another string (multiple times, if needed) until the resulting string reaches the given length.
  • repeat(count): Returns a new string which contains the specified number of copies of the original string.
  • split(separator): Splits the string into an array of substrings, using the specified separator to determine where to make the split.
  • indexOf(searchValue): Returns the index of the first occurrence of the specified substring. Returns -1 if not found.
  • lastIndexOf(searchValue): Returns the index of the last occurrence of the specified substring. Returns -1 if not found.
  • includes(searchValue): Determines whether the string contains the specified substring, returning true or false.
  • startsWith(searchValue): Checks if the string begins with the specified substring.
  • endsWith(searchValue): Checks if the string ends with the specified substring.
  • search(regexp): Search for a string pattern, which could be defined by a Regex. Returns the index of the first occurrence of the match or -1 if not found.
  • match(regexp): Search for a string pattern, which is defined by a Regex. If a global flag is included, it will return all occurrences of the pattern.
  • matchAll(regexp): Returns an iterable object containing all results matching a string against a global regular expression.
  • replace(regexp, newSubstr): Replaces occurrences of a pattern (specified by a regular expression) with a new substring.

If you want to learn more about JavaScript and web development, check out my new course at TheDevSpace.io.

Learn, Build & Launch

With Our Full Stack Dev Roadmap with Next.js Boilerplate

Start for FREE 🎉

Subscribe below to grab our free Full-Stack Web Developer Starter Kit 👇

Also follow us onorwhere we share coding tips daily.

Course Outline
Introduction+
  • 1.Course Introduction
HTML & CSS+
  • 1.Preparations
  • 2.HTML Elements
  • 3.Text Elements
  • 4.Layout Elements
  • 5.Cascading Style Sheet
  • 6.Basic Selectors
  • 7.Advanced Selectors
  • 8.Colors
  • 9.Loading Font
  • 10.Font Customization
  • 11.Text Customization
  • 12.Text Spacing
  • 13.Text Alignment
  • 14.Functions
  • 15.@ Rules
  • 16.Links
  • 17.Lists
  • 18.Tables
  • 19.Forms
  • 20.Form Fields
  • 21.Media Files
  • 22.Aspect Ratio
  • 23.Object Fit
  • 24.Cursor Behavior
  • 25.Scroll Behavior
  • 26.Visibility & Opacity
  • 27.Box Shadow
  • 28.Color Background
  • 29.Image Background
  • 30.Background Attachment
  • 31.Gradient
  • 32.Blend Modes
  • 33.The Box Model
  • 34.Border
  • 35.Padding & Margin
  • 36.Element Size
  • 37.Display Types
  • 38.Overflow
  • 39.Float
  • 40.Position
  • 41.Z index
  • 42.The Column Layout
  • 43.The Grid Layout
  • 44.Grid Flow
  • 45.Grid Gap
  • 46.Grid Spanning
  • 47.Grid Alignment
  • 48.The Flexbox Layout
  • 49.Flex Gap
  • 50.Flex Order
  • 51.Basis, Grow & Shrink
  • 52.Flexbox Alignment
  • 53.Calculator
  • 54.Filters
  • 55.Transforms
  • 56.Transition
  • 57.Transition Timing Functions
  • 58.Transition Delay
  • 59.Animations
  • 60.Animation Iteration Count
  • 61.Animation Direction
  • 62.Animation Fill Mode
  • 63.Responsive Design
  • 64.Viewport
  • 65.Media Query
  • 66.Responsive Media
  • 67.Responsive Text
  • 68.Responsive Layout (Flexbox)
  • 69.Responsive Layout (Grid)
  • 70.Responsive Layout (Legacy)
  • 71.Layout Without Media Query
  • 72.Recreating YouTube
  • 73.Building the Layout
  • 74.Building the Navbar
  • 75.Building the Sidebar
  • 76.Building the Main Section
JavaScript Fundamentals+
  • 1.Introduction
  • 2.Basic Syntax
  • 3.Variables
  • 4.Data Types
  • 5.Numbers & BigInt
  • 6.Strings
  • 7.Boolean Values
  • 8.Undefined & Null
  • 9.Type Conversion
  • 10.If Statements
  • 11.Switch Statements
  • 12.While Loops
  • 13.For Loops
  • 14.Introducing Functions
  • 15.Variable Scope
  • 16.Arrays
  • 17.Mutating Array
  • 18.Searching Array
  • 19.Sorting Array
  • 20.Looping Array
  • 21.Objects
  • 22.Looping Object
  • 23.JSON
  • 24.Symbols
  • 25.Maps
  • 26.Sets
  • 27.Define Functions
  • 28.Function Arguments
  • 29.Rest Parameter & Spread Syntax
  • 30.Error Handling
  • 31.Pure Functions
  • 32.Functions as Value
  • 33.Higher Order Functions
  • 34.Function Factory
  • 35.Function Currying
  • 36.Function Wrapper
  • 37.Recursion
  • 38.Closure
  • 39.Methods
  • 40.Investigating "this"
  • 41.Losing "this"
  • 42.Constructor Functions
  • 43.Getters & Setters
  • 44.Prototypes Introduction
  • 45.Creating Prototypes
  • 46.Inspecting Prototypes
  • 47.Constructor with Prototype
  • 48.The Class Notation
  • 49.Class Inheritance
  • 50.Static Properties
  • 51.Private Properties
  • 52.Object Oriented Programming
  • 53.A Banking App
  • 54.Working with Date
  • 55.The Math Object
  • 56.JavaScript Modules
  • 57.Throwing Errors
  • 58.Asynchronous Programming
  • 59.Promise
  • 60.Resolve Promise
  • 61.Promise Chaining
  • 62.Async & Wait
  • 63.Best Practices
JavaScript in the Frontend+
  • 1.The DOM Tree
  • 2.Selecting Elements in the DOM
  • 3.DOM Navigation
  • 4.Changing Elements
  • 5.Adding Elements
  • 6.Removing Elements
  • 7.Event Handling
  • 8.Event Propagation
  • 9.Some Common Events
  • 10.Image Slider: Creating HTML
  • 11.Image Slider: Adding Styles
  • 12.Image Slider: Adding Scripts
  • 13.Image Slider That "Slides"
  • 14.Regular Expressions
  • 15.Regex Flags
  • 16.Regex Matching Character Sets
  • 17.Regex Boundary
  • 18.Regex Groups & Quantifiers
  • 19.Regex Lookahead & Lookbehind
  • 20.Regex Related Methods
  • 21.Calculator
  • 22.Canvas
JavaScript in the Backend+
  • 1.Setting Up a Dev Environment
  • 2.Network & HTTP
  • 3.A Basic Web App
  • 4.Express.js
  • 5.Routing
  • 6.MVC Architecture
  • 7.The Model Layer
  • 8.CRUD Operations
  • 9.The Controller Layer
  • 10.The View Layer
  • 11.Blog
  • 12.ORM Integration
  • 13.Creating a Post
  • 14.Uploading Files
  • 15.Showing a Post
  • 16.Updating a Post
  • 17.Deleting a Post
  • 18.Database Relations
  • 19.CRUD Tags
  • 20.Adding & Removing Tags
  • 21.Showing Tags & Posts
  • 22.Middleware
  • 23.Browser Data Storage
  • 24.User Registration
  • 25.User Authentication
  • 26.User Authorization
  • 27.User Management
  • 28.Going to Production
React.js+
  • 1.Introducing React.js
  • 2.Setting Up React Project
  • 3.React Project Structure
  • 4.JSX
  • 5.Conditional Rendering
  • 6.List Rendering
  • 7.Adding Styles
  • 8.Components
  • 9.Import & Export Component
  • 10.Variables in Components
  • 11.Props
  • 12."children" Prop
  • 13.Event Handlers
  • 14.Event Handlers & Props
  • 15.Event Propagation
  • 16.Event Prevent Default
  • 17.Introducing State
  • 18.States are Local
  • 19.Object States
  • 20.Multiple States
  • 21.Shared States
  • 22.Form Handling
  • 23.Component Lifecycle
  • 24.Built-In Components
  • 25.Todo List
  • 26.Add New Task
  • 27.Remove Task
  • 28.Edit Task
  • 29.Complete a Task
  • 30.View Pending Tasks
  • 31.Organize State with Reducer
  • 32.The Reducer Function
  • 33.Dispatch Actions
  • 34.Passing Data with Context
  • 35.Context Provider
  • 36.Access Context
  • 37.Use Context with State
  • 38.Manipulate DOM with Refs
  • 39.Side Effects
  • 40.Side Effect Dependencies
  • 41.Side Effect Clean Up
  • 42.Weather App
  • 43.Get Weather by Coordinate
  • 44.Get Weather by City
  • 45.Display Weather by User Location
  • 46.Creating Custom Hooks
  • 47.Other React Hooks
  • 48.Rules of React
  • 49.Building a Full-Stack Blog App
  • 50.Project Setup
  • 51.React Router
  • 52.List Posts
  • 53.Create a New Post
  • 54.Show a Single Post
  • 55.Update a Post
  • 56.Delete a Post
  • 57.Implement Dark Theme
Full-Stack with Next.js+
  • 1.Next.js Basics
  • 2.Routing
  • 3.Pages & Layout
  • 4.Server vs. Client Components
  • 5.API Routes
  • 6.Server Actions
  • 7.Database Integration
  • 8.Data Fetching
  • 9.Error Handling
  • 10.Middleware
  • 11.Links, Navigation & Redirection
  • 12.Images
  • 13.Scripts
  • 14.Fonts
  • 15.Lazy Loading
  • 16.Caching
  • 17.Loading UI
  • 18.SaaS Platform
  • 19.User Authentication
  • 20.Magic Link
  • 21.Custom Emails
  • 22.Protecting Routes
  • 23.OAuth Providers
  • 24.Dashboard
  • 25.Role Based Access Control
  • 26.Payment Integration
  • 27.Pricing Page
  • 28.Stripe Checkout
  • 29.Payment Webhook
AI for Full-Stack Developers+
  • 1.What Are LLMs?
  • 2.Setting Up OpenAI Account
  • 3.Tokens
  • 4.Context Window
  • 5.Compare LLM Models
  • 6.OpenAI Model Playground
  • 7.Building a Chatbot
  • 8.Send Message to OpenAI
  • 9.Talking to GPT-4
  • 10.Talking to GPT-5
  • 11.Response Streaming
  • 12.Sending Data
  • 13.Receiving Data
  • 14.Streaming with Server Sent Events
  • 15.Chatbot Streaming Backend
  • 16.Chatbot Streaming Frontend
  • 17.Prompt Engineering
  • 18.System Prompt
  • 19.Role Switcher
  • 20.Prompting Techniques
  • 21.Structured Output
  • 22.Get Current Weather
  • 23.Tools & Functions
  • 24.Structured Output vs. Tool Calling
  • 25.What is an Agent
  • 26.What is RAG
  • 27.Chunking & Embedding
  • 28.Building a RAG Agent
  • 29.Setting Up the Database
  • 30.Document Processing
  • 31.Split Text into Chunks
  • 32.Generate Embeddings
  • 33.Listing Processed Documents
  • 34.Chat with RAG Agent
  • 35.Semantic Search
  • 36.Generate a Response
Recent Community Articles
  • The Ultimate Guide to Becoming an AI Engineer
  • How to Learn Full-Stack Web Development in 2025 (With Projects)
  • Top Website Optimization Methods in 2025
  • How to Build Interactive Forms Using HTML and CSS
  • How to Create a Modern App with Django and Vue
  • How to Send HTTP Requests Using JavaScript
  • Vue.js Fundamentals
  • How to Reverse a String in JavaScript
  • How to Reverse an Array in JavaScript
  • JavaScript Fundamentals 2025
  • How to extract a character from string
  • How to extract a substring
  • How to convert string to upper and lower cases
  • How to join two strings together
  • How to trim extra white spaces from string
  • How to add padding to string
  • How to repeat a string
  • How to split string into an array
  • How to search in a string
  • How to search in a string using Regex
  • How to replace a string pattern
  • Conclusion

Full Stack AI Dev

RoadmapCommunityPricing

SaaS Boilerplate

Next.js BoilerplateDocumentation

Contribute

Write for UsStyle Guide

Free Tools

HTML CompilerJavaScript CompilerNode.js CompilerReact CompilerNext.js Compiler

Legals

Privacy PolicyTerms of ServiceContact Us
© 2026TheDevSpace.io| All Rights Reserved
RoadmapSaaS BoilerplatePricingCommunity
CheatsheetsHTML CompilerJavaScript CompilerNode CompilerReact CompilerNext.js Compiler
Get Started
CourseNext.js BoilerplatePricingCommunity
Freebies
CheatsheetsHTML CompilerJavaScript CompilerNode CompilerReact CompilerNext.js Compiler