Sukanta Paul
Sukanta Paul

Reputation: 792

Replace all occurances in javascript

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:

Upvotes: 1

Views: 551

Answers (4)

Christoph
Christoph

Reputation: 51261

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");

Upvotes: 1

manman
manman

Reputation: 5113

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

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

Upvotes: 0

Joe
Joe

Reputation: 82654

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

Upvotes: 4

MKS
MKS

Reputation: 352

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');

Upvotes: 0

Related Questions