Bind Url Parameters and dynamically change later with javascript.
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.