Angular2 How to split string?

佐手、 提交于 2020-06-25 04:41:25

问题


Hi I am trying to split json string using possibly pipe? or I don't really know how to do it.

Right now I have json string of

"www.youtube.com||djlajdalksd.png||somethingsomething"

(These are just made up)

And I want to only get .png part.

How could I achieve this?


回答1:


Write a pipe:

@Pipe({ name: "splitAndGet" })
export class SplitAndGetPipe implements PipeTransform {
  transform(input: string, separator: string,index:number): string {
    return input.split(separator)[index];
  }
}

then in template:

{{"www.youtube.com||djlajdalksd.png||somethingsomething"|splitAndGet:"||":1}}

that will return "djlajdalksd.png"




回答2:


Just reference @n00dl3's answer, give an integrated version:

step1, using angular-cli to generate a pipe ng g pipe split

step2, modifying split.pipe.ts file:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'split'
})
export class SplitPipe implements PipeTransform {

  transform(input: string, sep: string, inx: number): string {
    return input.split(sep)[inx];
  }

}

then, in html

<span> {{hero.url | split:"/":4}} </span>


来源:https://stackoverflow.com/questions/43224957/angular2-how-to-split-string

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