Skip to content

Commit

Permalink
feat: add string sanitization function to remove special characters a…
Browse files Browse the repository at this point in the history
…nd format text

Implemented a TypeScript function `sanitizeTitle` that removes all special characters from a string, replaces spaces with dashes, and converts the string to lowercase. This is useful for generating URL-friendly strings from user input. Includes handling for diacritical marks and ensures consistent formatting.
  • Loading branch information
davidrdsilva committed May 30, 2024
1 parent fffcafe commit 091b7de
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/entities/blog.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,14 @@ export class Blog {
@Field(() => ID)
id: string;

@Column({ nullable: false })
@Column({ nullable: false, unique: true })
@Field(() => String)
title: string;

@Column({ nullable: false, unique: true })
@Field(() => String)
slug: string;

@Column({ nullable: false })
@Field(() => String)
description: string;
Expand Down
17 changes: 17 additions & 0 deletions src/providers/blog.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ export class BlogService {
private readonly storageClientService: StorageClientService,
) {}

private sanitizeTitle(title: string): string {
// Remove special characters and replace spaces with dashes
const sanitized = title
.toLowerCase() // Convert to lowercase
.normalize("NFD") // Normalize to NFD form to separate characters from their diacritical marks
.replace(/[\u0300-\u036f]/g, '') // Remove diacritical marks
.replace(/[^a-z0-9\s-]/g, '') // Remove special characters except for alphanumeric, spaces, and dashes
.trim() // Remove leading and trailing whitespace
.replace(/\s+/g, '-'); // Replace spaces with dashes

return sanitized;
}

async create(createBlogInput: CreateBlogInput, file: Express.Multer.File) {
const blog = new Blog();

Expand All @@ -22,8 +35,12 @@ export class BlogService {

// blog.filename = uploadedFile.filename;

// Generate slug
const slug = this.sanitizeTitle(createBlogInput.title);

blog.filename = 'image.png';
blog.title = createBlogInput.title;
blog.slug = slug;
blog.description = createBlogInput.description;
blog.body = JSON.parse(createBlogInput.body);
blog.tags = JSON.parse(createBlogInput.tags);
Expand Down

0 comments on commit 091b7de

Please sign in to comment.