JavaScript

Bind Url Parameters and dynamically change later with javascript.

Share your learning

I have created a few javascripts snippets to deal with UI pages data and links. Like the complete projects listing needs to be updated by using ajax.

So, I have created one constant js variable called APP_URL and set it in the header. After this I always create the required URLs in the beginning of the script and use those links where needed.

Single url parameter

In the following code we need to replace the {id} with actual project id when creating the project delete button.

let deleteProjectUrl = `${APP_URL}/projects/{id}/delete`;

function deleteProjectBtn( project ) {
     return `<a href=”${ bindUrl( deleteProjectUrl, project.id ) }” class=”btn btn-danger”>Delete</a>`; 
}

Multiple url parameters

This is the multiple url parameters example, so we need to replace {id} with project id and {invoice_id} with actual invoice id.

let projectInvoiceUrl  = `${APP_URL}/projects/{id}/invoices/{invoice_id}`;

function projectInvoiceBtn( project, invoice_id ) {
      return `<a href=”${ bindUrl( projectInvoiceUrl, [project.id, invoice_id] ) }” class=”btn btn-primary”>View</a>`; 
}

Solution to bind the url parameters

So, the following javascript method helps us to solve our problem. We are using regEx to replace the url parameters with actual values.

function bindUrl(url, params) {
    params = Array.isArray(params) ? params : [params];
    params.forEach(param => {
        url = url.replace(/\{\w+\}/, param);
    })
    return url;
}

That’s it, I hope you like it.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

11 months ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

11 months ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago