1

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:

Community
  • 1
  • 1
Sukanta Paul
  • 784
  • 3
  • 19
  • 36

4 Answers4

4

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
Joe
  • 80,724
  • 18
  • 127
  • 145
1

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");
Christoph
  • 50,121
  • 21
  • 99
  • 128
0

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');
MKS
  • 352
  • 3
  • 8
0

str = str.replace(/html/, 'php');

you shouldn't put single or double quotes for the first parameter.

manman
  • 4,743
  • 3
  • 30
  • 42