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:
var myOtherUrl =
"http://wikitechy.com/index.html?url=" + encodeURIComponent(myUrl);
click below button to copy the code. By JavaScript tutorial team
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.
$.param({a:"1=2", b:"Test 1"}) // gets a=1%3D2&b=Test+1
click below button to copy the code. By JavaScript tutorial team
Solution 4:
encodeURIComponent() is the way to go.
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
click below button to copy the code. By JavaScript tutorial team
- 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():
function urlencode(str) {
str = (str + '')
.toString();
// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if we want to reflect current
// PHP behavior, we would need to add ".replace(/~/g, '%7E');" to the following.
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.
replace(/\)/g, '%29')
.replace(/\*/g, '%2A')
.replace(/%20/g, '+');
}
click below button to copy the code. By JavaScript tutorial team
Solution 5:
Similar kind of thing we tried with normal javascript
function fixedEncodeURIComponent(str){
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}