13

I am trying to find all the characters ('?') of a URL and replace it with &.

For instance, i have var test = "http://www.example.com/page1?hello?testing";

I first attempted:

document.write(test.replace("&","?"))

This resulted in that only the first ? would be replaced by & , then I found a question saying that I could add a g(for global)

document.write(test.replace("&"g,"?"))

Unfortunately, this did not have any effect either.

So how do I replace all characters of type &?

Subhashi
  • 4,145
  • 1
  • 23
  • 22
Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

2 Answers2

5

You need to escape the ? character like so:

test.replace(/\?/g,"&")
EasyPush
  • 756
  • 4
  • 13
3

You're almost there.

the thing you saw in SO is regex replace :

document.write(test.replace(/\?/g,"&")) ( I thought you wanted to change & to ? , but you want the opposite.)

with the G flag - it will replace all the matches in the string

without it - it will replace only the first match.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792