Skip to content

Instantly share code, notes, and snippets.

@ruslanguns
Forked from coskuncakir/slugify.pipe.ts
Last active October 5, 2020 23:44
Show Gist options
  • Save ruslanguns/192bfb952df48325a1c15e648f88f0a7 to your computer and use it in GitHub Desktop.
Save ruslanguns/192bfb952df48325a1c15e648f88f0a7 to your computer and use it in GitHub Desktop.
Angular Pipe to transform a string into a slug with spanish character support.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'slugify' })
export class SlugifyPipe implements PipeTransform {
transform(input: string): string {
const trChars = {
'áÁ': 'a',
'éÉ': 'e',
'íÍ': 'i',
'óÓ': 'o',
'úÚ': 'u',
'ñÑ': 'n'
};
for (const key of Object.keys(trChars)) {
input = input.replace(new RegExp('[' + key + ']', 'g'), trChars[key]);
}
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'; //import it from your path
//your other imports
@Component({
selector: 'app-your-component',
templateUrl: './your-component.component.html',
styleUrls: ['./your-component.component.css'],
providers: [SlugifyPipe]
})
export class YourComponent{
constructor(private slugifyPipe: SlugifyPipe){}
slugify(input: string){
const 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