Encode string for URL (angular)

Solution 1:

HttpParameterCodec : is a codec for encoding and decoding parameters in URLs( Used by HttpParams).

If you need to encode Url you can use the below:

encodeURI assumes that the input is a complete URI that might have some characters which need encoding in it.

encodeURIComponent will encode everything with special meaning, so you use it for components of URIs, such as:

var textSample= "A sentence with symbols & characters that have special meaning?";
var uri = 'http://example.com/foo?hello=' + encodeURIComponent(textSample);

Solution 2:

Both encodeURI() and encodeURIComponent() will work, while there are some differences:

var set1 = ";,/?:@&=+$";  // Reserved Characters
var set2 = "-_.!~*'()";   // Unescaped Characters
var set3 = "#";           // Number Sign
var set4 = "ABC abc 123"; // Alphanumeric Characters + Space

console.log(encodeURI(set1)); // ;,/?:@&=+$
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // #
console.log(encodeURI(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // %23
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encoded as %20)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent