Replace all occurances in javascript

2019-08-03 04:55发布

问题:

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

回答1:

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


回答2:

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


回答3:

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


回答4:

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

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