logohahid

JavaScript Snippets

Following are some of the useful JavaScript snippets I used on some of my projects.

Generate slug

function generateSlug(text: string) {
    return `${text
        .trim()
        .replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '')
        .replace(/\s+/g, '-')
        .toLowerCase()}`;
}

const postHeader = "Load Google Analytics (Gtag) Efficiently In Gatsby Site";
const slug = generateSlug(postHeader);

console.log(slug);

// Output: load-google-analytics-gtag-efficiently-in-gatsby-site

Replace multiple words

const correctNames = {
    aws: 'AWS',
    s3: 'S3',
    github: 'GitHub',
    javascript: 'JavaScript',
    gatsby: 'Gatsby',
} as const;

function replaceWithCorrectNames(text: string, correctWords: Record<string, string>) {
    const pattern = new RegExp(Object.keys(correctWords).join('|'), 'gi');

    return text.replace(pattern, function (matched) {
        return correctWords[matched.toLowerCase()];
    });
}

const myString = "This article is about how we can use github action to deploy a gatsby site written in javascript to aws s3.";

const correctedString = replaceWithCorrectNames(myString, correctNames);

console.log(correctedString);

// Output: This article is about how we can use GitHub action to deploy a Gatsby site written in JavaScript to AWS S3.