Encode string for URL (angular)

user749798 picture user749798 · Mar 29, 2019 · Viewed 51.2k times · Source

I'm trying to encode a string that's pretty complex, so that I can include it in a mailto:

Component:

<a href="mailto:[email protected]?subject='Hello'&{{body}}">

TS:

import { HttpParameterCodec } from "@angular/common/http";

let body = encodeValue('This is the example body\nIt has line breaks and bullets\n\u2022bullet one\n\u2022bullet two\n\u2022bullet three')

When I try to use encodeValue, I get "cannot find name encodeValue.

How would be best to url-encode body?

Answer

nircraft picture nircraft · Mar 29, 2019

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);