Skip to content

Instantly share code, notes, and snippets.

@djabif
Last active April 12, 2023 21:34
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • 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);
}
}
@anelad
Copy link

anelad commented Sep 12, 2019

Thanks! But this does not replace Turkish chars like ü ö ğ ç ı ş.

@coskuncakir
Copy link

coskuncakir commented Sep 27, 2019

Hi, thanks @djabif. @anelad I implemented Turkish character support here: https://gist.github.com/coskuncakir/3378d0147968e4297eb20a1d214296eb

@djabif
Copy link
Author

djabif commented Sep 28, 2019

thanks @coscakir!

@anelad
Copy link

anelad commented Oct 12, 2019

thanks @coscakir!

@Nicksideal
Copy link

Thank you so much for this! Spent 4 hours+ trying to understand replace () in Angular to create this specific pipe!

@LeRoiDavid
Copy link

Thank you !

@ruslanguns
Copy link

For Spanish Language you have this one https://gist.github.com/ruslanguns/192bfb952df48325a1c15e648f88f0a7 based in the sample of @coscakir

@tobyokeke
Copy link

thanks

@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