I've searched through different websites showing me the way to replace strings in js. But actually its not working! Why?
The code I'm using:
var str = "This is html. This is another HTML";
str = str.replace('/html/gi','php');
Output: This is html. This is another html
Nothing is changing. Its Frustrating!
References I've used:
- How to Replace All Occurrences of a String using Javascript Replace
Function
- How to replace all points in a string in JavaScript
No quotes:
str = str.replace(/html/gi,'php');
The RegExp object can be expressed in its literal format:
/I am an actual object in javascript/gi
remove the quotes to make it work. //
is a regex and may not be quoted.
str = str.replace(/html/gi,'php');
Alternatively you could write:
str = str.replace(new RegExp('html','gi'),'php');
The non standard conform method would be this (works only in some browsers, not recommended!)
str.replace("apples", "oranges", "gi");
Remove the single quote from your regular expression like so:
var str = "This is html. This is another HTML";
str = str.replace(/html/gi,'php');
str = str.replace(/html/, 'php');
you shouldn't put single or double quotes for the first parameter.