从 TypeScript 中的字符串中删除所有空格 – 码微 |
您所在的位置:网站首页 › vue去除字符串前后空格 › 从 TypeScript 中的字符串中删除所有空格 – 码微 |
从 TypeScript 中的字符串中删除所有空格
Remove all Whitespace from a String in TypeScript
使用该replace()方法从 TypeScript 中的字符串中删除所有空格,例如str.replace(/\s/g, ''). 该replace方法采用正则表达式和替换字符串作为参数。该方法将返回一个删除了所有空格的新字符串。 索引.ts const str = ' one two three '; // ✅ Remove all Whitespace const withoutAnyWhitespace = str.replace(/\s/g, ''); console.log(withoutAnyWhitespace); // 👉️ "onetwothree" // ✅ Remove only leading and trailing whitespace const result = str.trim(); console.log(result); // 👉️ "one two three"我们使用该replace()方法从字符串中删除所有空格。 我们将以下 2 个参数传递给 String.replace 方法: 我们要在字符串中匹配的正则表达式。 每场比赛的替补。正斜杠/ /标记正则表达式的开始和结束。 元\s字符匹配spaces,tabs和newlines。 我们使用g(global) 标志来指定我们要匹配字符串中所有出现的空白字符,而不仅仅是第一次出现。该replace方法采用的第二个参数是替换。在我们的例子中,我们想用空字符串(无)替换所有空格。 请注意,该String.replace方法不会更改原始字符串,它会返回一个新字符串。字符串在 JavaScript(和 TypeScript)中是不可变的。 如果您只需要从字符串中删除前导和尾随空格,请使用 String.trim() 方法。 索引.ts const str = ' one two three '; // ✅ Remove leading and trailing whitespace const result = str.trim(); console.log(result); // 👉️ "one two three"该trim()方法将删除字符串两端的空格并返回一个新字符串。 该方法不修改原始字符串,它返回一个新字符串。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |