4

How can I escape & (ampersand) in url with the correct replacement in the jQuery function. I have tried

.replace("/&/g", "&")  
.replace("/&/g", "%26") 
.replace("/&/g", "\&") 

But nothing is working.

If anyone has idea please share with me.

Thanks

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
alienavatar
  • 277
  • 1
  • 6
  • 19
  • `.replace(/&/g, "%26")` should work if your JS is external. If it's embedded in your HTML, then you probably need to escape the `&` as `&`. But, use `encodeURIComponent` instead of reinventing the wheel. – Ates Goral Jun 21 '10 at 18:07
  • 1
    This really has nothing to do with jQuery - string replacement operations are plain old JavaScript – gnarf Jun 21 '10 at 18:21

2 Answers2

9

If you need to just escape a URL, I recommend using a JavaScript function such as encodeURIComponent.

MANJEET
  • 1,733
  • 2
  • 12
  • 21
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
2

Try the URLEncode plugin: http://plugins.jquery.com/project/URLEncode

Chris Schmitz
  • 8,097
  • 6
  • 31
  • 41
  • 1
    Really? Someone made a plugin for this? Whats wrong with the standard JS function [`encodeURIComponent()`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent) – gnarf Jun 21 '10 at 18:23