URL的编码字符串(角度)

use*_*798 9 url encode angular

我正在尝试编码一个非常复杂的字符串,以便可以将其包含在mailto中:

零件:

<a href="mailto:test@example.com?subject='Hello'&{{body}}">
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

当我尝试使用encodeValue时,出现“找不到名称encodeValue。

如何最好对主体进行url编码?

fis*_*ick 38

encodeURI() 和 encodeURIComponent() 都可以工作,但有一些区别:

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)
Run Code Online (Sandbox Code Playgroud)

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


nir*_*aft 10

HttpParameterCodec :是用于对URL中的参数进行编码和解码的编解码器(由HttpParams使用)。

如果您需要对网址进行编码,则可以使用以下代码:

encodeURI 假设输入是一个完整的URI,其中可能包含一些需要编码的字符。

encodeURIComponent 会使用特殊含义对所有内容进行编码,因此您可以将其用于URI组件,例如:

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