Skip to content

Instantly share code, notes, and snippets.

@djabif
Last active June 28, 2024 21:59
Show Gist options
  • Save djabif/b8d21c4ebcef51db7a4a28ecf3d41846 to your computer and use it in GitHub Desktop.
Save djabif/b8d21c4ebcef51db7a4a28ecf3d41846 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);
}
}
@geetika-kathuria
Copy link

Thank you!

@rahiyansafz
Copy link

could you show the full implementation?

@mklickman
Copy link

This is amazing, exactly what I needed! Can't believe this doesn't come with Angular by default 🤔 Thank you!

@djabif
Copy link
Author

djabif commented Nov 8, 2021

This is amazing, exactly what I needed! Can't believe this doesn't come with Angular by default 🤔 Thank you!

Thanks 😍

@tommydunn
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment