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
  • 3,899
  • 1
  • 21
  • 21
Marc Rasmussen
  • 18,255
  • 71
  • 189
  • 330

2 Answers2

5

You need to escape the ? character like so:

test.replace(/\?/g,"&")
EasyPush
  • 756
  • 3
  • 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
  • 138,711
  • 129
  • 435
  • 755