-3

In javascript how it's possible to replace all occurrence of &,<,> in a string

I tried this

 var str="<>&";
 str.replace("&","&amp").replace("<","&lt").replace(">","&gt");

but not able to change even first occurrence

4
  • 1
    String string is a syntax error. Is this Java? Commented Sep 15, 2017 at 13:05
  • 1
    replace returns the string so you need to use that variable which is returned by replace...and also this is not javascript Commented Sep 15, 2017 at 13:07
  • my bad corrected it Commented Sep 15, 2017 at 13:07
  • Usually you can replace all occurrences with Regex replace. Commented Sep 15, 2017 at 13:08

1 Answer 1

-1

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
re = new RegExp(pattern, "g");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.