banner

All About “replace” function in JavaScript

replace

replace function in JavaScipt

replace function is one of the main functions available for string manipulation in JavaScript. And it is one of the most used function. Now lets see the capabilities of that function, and common questions about that function.

var str = "This is a text of text contain all text";
str.replace("text", "loupe")

The result will be “This is a loupe of text contain all text” . The first occurrence of that variable is getting replaced.

How to use replace all in JavaScript? Or How to replace all the occurrence of a string in JavaScript?

This is a very common question, everybody asks. We can implement replace all functionality with the help of “replace” function in JavaScript. For that, we must use regular expressions.
var str = "This is a text of text contain all text";
str.replace(/text/gi,"loupe")

So the result will be “This is a loupe of loupe contain all loupe“. 

How we can pass a variable into a regular expression?

This is again another common doubt, people asks during development.
var txt = "text"
var myreplace = new RegExp(txt,"gi");
code = code.replace(myreplace ,"loupe");

0

Article Tags:
· · · ·
Article Categories:
JavaScript · Programming
Likes:
0

Leave a Comment

Your email address will not be published. Required fields are marked *