【问题标题】:Encode string for URL (angular)URL 的编码字符串(角度)
【发布时间】:2019-08-20 13:38:45
【问题描述】:

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

组件:

<a href="mailto:test@example.com?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')

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

如何最好地对正文进行 url 编码?

【问题讨论】:

  • 首先,您可以使用 JavaScript 的 encodeURI 函数来编码您的文本。 (如果您使用的字符之一 - ;,/?:@&amp;=+$#,请改用encodeURIComponent 函数。)
  • 这在项目符号或换行符上不起作用
  • 它是用于 URI 的

标签: angular url encode


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

    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)

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

    【讨论】:

      猜你喜欢
      • 2017-06-17
      • 2020-04-11
      • 1970-01-01
      • 2014-02-19
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      相关资源
      最近更新 更多