Angular2 split string (pipe?)

后端 未结 2 1199
你的背包
你的背包 2021-01-06 16:10

Is it possible to use something similar to {{mystr | split(last) }} somehow?

I\'m hoping there is a pipe included already.

相关标签:
2条回答
  • 2021-01-06 16:42

    You need a custom pipe for this. You could implement this this way:

    @Pipe({
      name: 'split'
    })
    export class SplitPipe implements PipeTransform {
      transform(val:string, params:string[]):string[] {
        return val.split(params[0]);
      }
    }
    

    and use it like this:

    {{mystr | split:last }}
    

    where last is a property of your component that corresponds to the separator.

    0 讨论(0)
  • 2021-01-06 16:52

    I'm not sure what last is. I'll guess that you mean you want the last set of characters from the string, if you split the string up by some separator. E.g., if the string is abc,def,ghi and the separator is , then you want ghi.

    @Pipe({ name: 'splitLast' })
    export class SplitLastPipe implements PipeTransform {
      transform(value:string, [separator]):string {
        let splits = value.split(separator);
        if(splits.length > 1) {
          return splits.pop();
        } else {
          return '';
        }
      }
    }
    

    {{mystr | splitLast:','}}
    

    Plunker

    0 讨论(0)
提交回复
热议问题