3

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

2 Answers 2

6

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"

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting Type 'string' is not assignable to type 'any[]'.) error
if I use {{"www.youtube.com||djlajdalksd.png||somethingsomething"|splitAndGet:"||",1}} like this I get Template parse errors: Parser Error: Unexpected token ',' which is caused by that , after saperator
3

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.