How to remove whitespace in text

后端 未结 5 1208
夕颜
夕颜 2021-01-17 18:01

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

Example

{{ someobject.name }}  

someobject.name results in \"name abc\"

相关标签:
5条回答
  • 2021-01-17 18:13

    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, "");
    
    0 讨论(0)
  • 2021-01-17 18:14

    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");
    
    0 讨论(0)
  • 2021-01-17 18:23

    Replace all the whitespace between string

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

    let str = "name abc"

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

    0 讨论(0)
  • 2021-01-17 18:23

    In my case this is bad:

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

    Solution:

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

    =S

    0 讨论(0)
  • 2021-01-17 18:24
    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, "");
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题