【问题标题】:Angular - How can i raplace whole caracter in entire JSON?Angular - 如何替换整个 JSON 中的整个字符?
【发布时间】:2018-10-12 08:13:22
【问题描述】:

我刚刚找到了一种通过我的 URL 传递 & 符号的方法,但目前我只能替换我的第一个字符。

我的json是这样的:

{
  "post_ID": 0,
  "post_date": "2018-10-12",
  "post_content": "Post content test",
  "post_image": "example.png",
  "article_tittle": "Article tittle test",
  "article_content": "<p>first &amp;</p><p>second &amp;</p>",
  "post_category": "INF"
}

这是我的角度代码

addPost(post: Post) {
  let json = JSON.stringify(post);
  let params = 'json=' + json.replace('&', '%26');
  //let params = 'json='+json;
  let headers = new Headers({
    'Content-Type': 'application/x-www-form-urlencoded'
  });

  return this._http.post(this.url + 'posts', params, {
      headers: headers
    })
    .pipe(map((res: Response) => res.json()));
}

('&','%26');将替换我的第一个 & 但不是第二个 &,我必须创建第二个数组才能处理整个文本?

【问题讨论】:

    标签: json angular angular6


    【解决方案1】:

    你可以像这样使用正则表达式

    let params = 'json='+json.replace(new RegExp('&', 'g'), '%26');
    

    【讨论】:

    • 或者字面意思:json.replace(/&amp;/g, '&amp;26')
    • 我可以确认 firegloves 建议的正则表达式可以正常工作。干杯!
    • 或者您可以使用来自@angular/common/httpHttpParams,它将对您所有的“错误”字符进行编码...
    【解决方案2】:

    我认为您可以通过使用 encodeURI 创建您的 queryParamsdecodeURI 来取回原始对象来做到这一点。

    const queryParams = {
      "post_ID": 0,
      "post_date": "2018-10-12",
      "post_content": "Post content test",
      "post_image": "example.png",
      "article_tittle": "Article tittle test",
      "article_content": "<p>first &amp;</p><p>second &amp;</p>",
      "post_category": "INF"
    };
    
    const encoded = encodeURI(JSON.stringify(queryParams));
    ...
    const decodedObject = JSON.parse(decodeURI(encoded));
    
    ...
    
    addPost(post: Post) {
    
      const params = `json=${encodeURI(JSON.stringify(post))}`;
    
      let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
      });
    
      return this._http.post(this.url + 'posts', params, {
          headers: headers
        })
        .pipe(map((res: Response) => res.json()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多