Lea
Lea

Reputation: 1285

Angular2 How to split string?

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?

Upvotes: 3

Views: 9136

Answers (2)

Belter
Belter

Reputation: 3837

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>

Upvotes: 3

n00dl3
n00dl3

Reputation: 21584

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"

Upvotes: 6

Related Questions