Categories: Tutorials

Javascript Function to Replace All Occurances of String

Javascript has a “replace” method which can be used to replace all occurances of a string. Consider for example that you want to replace all the occurances of the word “Miscellaneous” to “Amazing”.

var originalStr = 'This is a Miscellaneous Post. Miscellaneous posts will be put here.';
var newStr = originalStr.replace('Miscellaneous','Amazing');
alert(newStr);

If we run the above code then it will replace first occurance of “Miscellaneous” to “Amazing”. And it will return from there without modifying further occurances.

So to replace all occurances we should use regular expression. String.replace method of JavaScript allows us to specify regular expression as the first parameter.

Lets modify our existing code to use regular expression and replace all “Miscellaneous” to “Amazing”.

var originalStr = 'This is a Miscellaneous Post. Miscellaneous posts will be put here.';
var newStr = originalStr.replace(/Miscellaneous/gi,'Amazing');
alert(newStr);

Now above code will replace all occurances of a string in JavaScript.

We have added “g” identifier at the end of the regular expression to match it globally and perform replace operation. Even we have added “i” identifier, it will do “case insensitive” replacing, matching “Miscellaneous”, “miscellaneous” etc.

ProWebGuru

Mostly I write about technology related stuff on https://www.prowebguru.com Recently I have started making videos also. Mostly blog posts & videos are related to technology, programming and learning some new tips and tricks related to windows, wordpress, google app script, technical, programming, javascript, jquery and other coding related stuff. Youtube channel - https://www.youtube.com/user/prowebguru

Recent Posts

GPT 5.4: Powerful AI Breakthrough – 7 Game-Changing Features, Launch Date & Full Guide

GPT 5.4: The Next-Generation AI Model Transforming Reasoning, Coding, and Productivity Artificial Intelligence is evolving…

1 day ago

GPT‑5.3 Instant Explained: Faster, Smarter & Fewer Refusals

GPT-5.3 Instant is OpenAI's latest ChatGPT model update, prioritizing smoother conversations, fewer refusals, and higher…

2 days ago

Free Perplexity Pro for Airtel Customers: Unlock Advanced AI Assistance at No Cost!

Are you tired of scrolling endlessly through Google results trying to find clear, trustworthy answers?…

4 months ago

Unlocking Collaborative Coding with GitHub Copilot Spaces

In recent years, the process of software development has rapidly evolved—developers demand smarter tools and…

4 months ago

ChatGPT Go Now Free in India: Opening Doors to Advanced AI Capabilities

India has emerged as one of the fastest-growing and most significant markets in the global…

4 months ago

AgentKit by OpenAI: Redefining the Future of AI Agent Development

On October 6, 2025, OpenAI unveiled AgentKit, a unified suite of tools designed to help developers and…

5 months ago

This website uses cookies.