Skip to content

Instantly share code, notes, and snippets.

@tommydunn
Forked from djabif/slugify.pipe.ts
Created April 12, 2023 21:05
Show Gist options
  • Save tommydunn/d84de97fd448311547eaacaeb071437e to your computer and use it in GitHub Desktop.
Save tommydunn/d84de97fd448311547eaacaeb071437e to your computer and use it in GitHub Desktop.
Angular Pipe to transform a string into a slug
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'slugify'})
export class SlugifyPipe implements PipeTransform {
transform(input: string): string {
return input.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
}
import { SlugifyPipe } from '../../shared/slugify.pipe';
//remember to add this pipe as a module provider. In my case it is declared as a provider in my SharedModule
@Component({
//...
})
export class YourComponent{
constructor(private slugifyPipe: SlugifyPipe){}
slugify(input: string){
var your_new_slug = this.slugifyPipe.transform(input);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment