Angular2 split string (pipe?)

2020-03-05 03:13发布

问题:

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

I'm hoping there is a pipe included already.

回答1:

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.



回答2:

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



标签: split angular