typescript 如何去除文本中的空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49236726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove whitespace in text
提问by Babulaas
How can I trim a text string in my Angular application?
如何在我的 Angular 应用程序中修剪文本字符串?
Example
例子
{{ someobject.name }}
someobject.name results in "name abc"
someobject.name 结果为“名称 abc”
What I like to achieve is name to be "nameabc" (remove all whitespaces).
我想要实现的是名称为“nameabc”(删除所有空格)。
I already created a pipe and included this in the typescript file and module)
我已经创建了一个管道并将其包含在打字稿文件和模块中)
PIPE:
管道:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: 'trim' })
export class TrimPipe implements PipeTransform {
transform(value: any) {
if (!value) {
return '';
}
return value.trim();
}
}
{{ someobject.name | trim }} still results in "name abc" instead of "nameabc" }}
{{ someobject.name | 修剪}} 仍然会导致“name abc”而不是“nameabc”}}
回答by Matt
According to the docs, the trim() method removes trailingand leadingwhitespaces, not those in the middle.
根据文档,trim() 方法删除尾随和前导空格,而不是中间的空格。
https://www.w3schools.com/Jsref/jsref_trim_string.asp
https://www.w3schools.com/Jsref/jsref_trim_string.asp
If you want to remove all whitespaces use the replace
function:
如果要删除所有空格,请使用以下replace
函数:
"name abc".replace(/\s/g, "");
回答by tomichel
trim() only removes whitespaces from the start and end of a string:
trim() 只删除字符串开头和结尾的空格:
https://www.w3schools.com/Jsref/jsref_trim_string.asp
https://www.w3schools.com/Jsref/jsref_trim_string.asp
have a look here to remove whitespaces between strings:
看看这里删除字符串之间的空格:
Replace all whitespace characters
the relevant part is to use it like:
相关部分是像这样使用它:
str = str.replace(/\s/g, "X");
回答by Saurabh Bhoyar
Replace all the whitespace between string
替换字符串之间的所有空格
let spaceReg = new RegExp(" ",'g');
let spaceReg = new RegExp(" ",'g');
let str = "name abc"
let str = "name abc"
str = str.replace(spaceReg,"");
str = str.replace(spaceReg,"");
回答by Nirav
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'removeWhiteSpace'
})
export class RemoveWhiteSpacePipe implements PipeTransform {
transform(value: any): any {
if (value === undefined)
return 'undefined';
return value.replace(/\s/g, "");
}
}
回答by Hector
In my case this is bad:
就我而言,这很糟糕:
<div>
{{ someobject.name }}
</div>
Solution:
解决方案:
<div>{{ someobject.name}}</div>
=S
=S