【问题标题】:How to remove whitespace from a string in typescript? [duplicate]如何从打字稿中的字符串中删除空格? [复制]
【发布时间】:2018-08-15 03:53:03
【问题描述】:

在我的 Angular 5 项目中,我使用打字稿在这样的字符串上使用 .trim() 函数,但它没有删除空格,也没有给出任何错误。

this.maintabinfo = this.inner_view_data.trim().toLowerCase();
// inner_view_data has this value = "Stone setting"

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-4.html 这个文档清楚地说.trim() 是打字稿的一部分。

从打字稿中的字符串中删除空格的最佳方法是什么?

【问题讨论】:

  • 试试.toString().trim()

标签: angular typescript trim


【解决方案1】:

问题

trim() 方法删除字符串两边的空格。

Source

解决方案

您可以使用 Javascript 替换方法来删除空格,例如

"hello world".replace(/\s/g, "");

示例

var out = "hello world".replace(/\s/g, "");
console.log(out);

【讨论】:

【解决方案2】:

trim() 方法删除字符串两边的空格。

要删除字符串中的所有空格,请使用.replace(/\s/g, "")

 this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();

【讨论】:

  • 假设变量在一个字符串中有很多单词 var str = "你好,你好吗?";我怎样才能删除这里的空间?
  • 这将删除所有空格、尾随、前导以及中间的空格。
【解决方案3】:

Trim 只是删除尾随和前导空格。如果只需要替换空格,请使用 .replace(/ /g, "")。

this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 2022-01-24
    • 1970-01-01
    • 2013-12-11
    • 2011-12-07
    • 2021-09-04
    • 2017-04-14
    • 2020-02-02
    相关资源
    最近更新 更多