How to Replace a String or Substring in JavaScript?

Are you ready to discover how to replace a string or substring in JavaScript? Read on!

In this article, you’ll learn about the powerful replace() method, understand its syntax and parameters, and see practical examples of how it can be used in different scenarios.

So, without further ado, let’s dive into practical examples and learn how to manipulate strings like a pro.

What is replace() method in JavaScript?

The replace() method in JavaScript is used to return a new string with some or all matches of a pattern replaced by a replacement.

It can be a string or a RegExp (regular expression) and you can use a word or a special function to decide what the new parts will be.

In other words, The replace() method allows you to substitute a part of a string with something else.

This “something else” could be a different string or the result of a function.

Syntax

string.replace(searchValue, newValue)

Parameters

searchValue (Required)

It’s the value or regular expression to search for.

newValue (Required)

It is the new value you want to replace with.

Return value

A new string, with some or all matches of a pattern replaced by a replacement.

Here’s an example:

let oldsamplestring = "Welcome to Amazingworld!";
let newsamplestring = oldsamplestring.replace("Amazingworld", "Itsourcecode"); ✅
console.log(newsamplestring);  

Output:

Welcome to Itsourcecode!

📌Keep in mind that the replace() method doesn’t modify the original sentence. If you need to switch out all occurrences of a word, you’ll need to use a regular expression with the ‘g’ modifier.

How to use replace() method to replace a String or Substring in JavaScript?

Here’s how you can use the replace() method in JavaScript to replace a string or substring:

Replacing a simple string

Here’s an example:

let samplestr = "Hi, welcome to Universe!";
let newStr = samplestr.replace("Universe", "Itsourcecode"); 
console.log(newStr);

As you can see, we’re replace the word “Universe” with “Itsourcecode.” The replace() method returns a new string and does not modify the original string.

Output:

Hi, welcome to Itsourcecode!

Replacing a substring using a regular expression

You have the option to utilize the replace() method alongside regular expressions. It allows you to replace not only complete words but also parts of words, granting you greater flexibility and control.

Here’s an example:


let samplestr = "Today is a family day. I love family day!";
let newStr = samplestr.replace(/family/g, "Christmas"); ✅

console.log(newStr);

As you can see, we use the regular expression /family/g to find all occurrences of the word of the substring “family” in the samplestr.

When you include the “g” flag, it means you want to replace all the matches. The replacement string “Christmas” replaces all matched substrings, resulting in the newStr.

Output:

Today is a Christmas day. I love Christmas day!

Here’s another example example:

let samplestr = "I love math. Math is my favorite subject.";
let newStr = samplestr.replace(/Math/gi, "Programming"); 
console.log(newStr); 

Here, we replace all occurrences of the subject “Math” with “Programming.”

We use a regular expression /Math/gi to find all occurrences of the word ” Math,” regardless of the case. It is because the /i flag is used in a case-insensitive search.

(That’s why we used the “i” flag here), and replace them with “Programming.”

Output:

I love Programming. Programming is my favorite subject.

Replacing a substring using a function

You can also pass a function as the second argument to the replace() method. This function’s return value will be used as the replacement string.

Here’s an example:

let samplestr = "I have 2 cookies in my bag.";
let newStr = samplestr.replace(/\d+/, function(match) { 
    return parseInt(match) * 2;
});
console.log(newStr); 

In this example, we used regular expression to match any sequence of digits in the string (which represents the number of cookies).

The matched substring is passed to the function, where it’s doubled and returned. The replace() method then uses this return value as the replacement string.

Output:

I have 4 cookies in my bag.

Replacing multiple different substrings

If you want to replace multiple different substrings in a string, you can chain replace() methods:


let samplestr = "I love Math and English subjects.";
let newStr = samplestr.replace("Math", "Programming").replace("English", "Software Engineering"); ✅
console.log(newStr);

In this example, we replace “Math” with “Programming” and “English” with “Software Engineering.”

Each replace() method returns a new string, so you can chain them together to perform multiple replacements.

Output:

I love Programming and Software Engineering subjects.

Conclusion

The replace() method in JavaScript is used to replace a string or substring with another string or the result of a function.

This method is versatile and can be used with simple strings or regular expressions for more complex patterns.

Remember, the replace() method does not modify the original string but returns a new string with the replacements.

It makes it a safe operation that won’t accidentally alter your original data.

Whether you’re replacing simple strings, using regular expressions, or passing a function as an argument, the replace() method offers flexibility and control in handling string replacements.

We are hoping that this article provides you with enough information that help you understand how to replace substring in JavaScript.

If you want to dive into more JavaScript topics, check out the following articles:

Thank you for reading Itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment