1

I was wondering if it is possible to trim file extensions from an array on Angular 2 TS.

I know it is easy to trim within JS, but wondered how easy it is to do within TS.

Lets same i have this data returned:

[ '1111111.pdf', '1111112.pdf' ]

How would I approach to trim the '.pdf' from the array?

I know in js you can use String.prototype.trim.apply but yano... any suggestions would be apprecaited

4 Answers 4

2

I'd use custom pipe.

Working Demo: https://plnkr.co/edit/I45tLyFfXyjKIq5A7Mqu?p=preview

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

@Pipe({ name: 'extension' })

export class RemoveExtension implements PipeTransform {
  transform(item) {
    return item.substring(0, item.indexOf('.'))
  }

}

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `      
      <h1>Remove Extension:</h1>      
      <li *ngFor="let item of myData">{{item|extension}}</li>
  `
})
export class AppComponent {
 myData=[ 'abc.pdf', 'xyz.pdf' ];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Brilliant did not realise a pipe could be so effective in that way! Helps alot! Question ... so {{item|extension}} was value (1111111.pdf) and now its (1111111) so if i then submitted a form with the pipe added would the value be with or without the extension? It should be without correct?
Depends on how you use form with reactiveForms.This pipe only trims required value that's it.
okay cool i will play around but i appreciate the custom pipe!
1

Typescript is just an extension of javascript, as such all standard javascript calls are available.

However in this instance trim would just remove whitespace, not file extensions.

The best way to handle this is to use "map" which will enumerate the array, then use a regex to remove the file extension.

The following should do the trick;

var myFileArray = ['1111111.pdf', '1111112.pdf'].map(function (e) {
    return e.replace(/\.[^/.]+$/, "");
});

1 Comment

Thanks for your reply it works well but the pipe provided proves to be more efficient, but i appreciate the answer and will upvote as it works just as well. thanks!
1
var displyName = fileName.substr(0, fileName.lastIndexOf('.'));

This code segment did the magic for me.

Comments

0

You should try to with lastIndexOf because . could be used at any place of file. So for making sure your code would work on every file try with the lastIndexOf.

     transform(value: any) {
        length = value.lastIndexOf('.');
        return value.slice(0, length)
    }

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.