How to remove whitespace in text

人走茶凉 提交于 2019-12-01 16:52:16

问题


How can I trim a text string in my Angular application?

Example

{{ someobject.name }}  

someobject.name results in "name abc"

What I like to achieve is name to be "nameabc" (remove all whitespaces).

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" }}


回答1:


According to the docs, the trim() method removes trailing and leading whitespaces, not those in the middle.

https://www.w3schools.com/Jsref/jsref_trim_string.asp

If you want to remove all whitespaces use the replace function:

"name abc".replace(/\s/g, "");



回答2:


trim() only removes whitespaces from the start and end of a string:

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");



回答3:


Replace all the whitespace between string

let spaceReg = new RegExp(" ",'g');

let str = "name abc"

str = str.replace(spaceReg,"");




回答4:


In my case this is bad:

<div>
  {{ someobject.name }}
</div>

Solution:

<div>{{ someobject.name}}</div>

=S



来源:https://stackoverflow.com/questions/49236726/how-to-remove-whitespace-in-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!