javascript tutorial - [Solved-5 Solutions] Encode URL in javascript - javascript - java script - javascript array
Problem:
How do we safely encode a URL using JavaScript such that it can be put into a GET string?
Solution 1:
built-in function encodeURIComponent(str) and encodeURI(str). In your case, this should work:
Solution 2:
We have three options:
- escape() will not encode: @*/+
- encodeURI() will not encode: ~!@#$&*()=:/,;?+'
- encodeURIComponent() will not encode: ~!*()'
But in your case, if we want to pass a URL into a GET parameter of other page, we should use escape or encodeURIComponent, but not encodeURI.
Solution 3:
If we are using jQuery WE would go for $.param method. It URL encodes an object mapping fields to values, which is easier to read than calling an escape method on each value.
Solution 4:
encodeURIComponent() is the way to go.
- But we should keep in mind that there are small differences from php version urlencode() and as @CMS mentioned, it will not encode every char. Guys at made js equivalent to phpencode():
Solution 5:
Similar kind of thing we tried with normal javascript