Languages
[Edit]
EN

JavaScript - fill path pattern with path variables

10 points
Created by:
christa
600

In this short article, we would like to show how to fill path pattern with path variables in JavaScript.

The main idea of the article is to show how:

  • for path pattern 'some/item/{path.to.id}/remove',
  • and path variable path.to.id equal to 123,
  • get path 'some/item/123/remove'.

Quick solution (in modern ES):

// ONLINE-RUNNER:browser;

const getProperty = (data, path) => {
    const parts = path.split('.');
    return parts.reduce((data, key) => data?.[key], data);
};

const renderPath = (pathPattern, entityData) => {
    return pathPattern.replace(/\{([\w.]+)\}/g, (match, variablePath) => {
        const variableValue = getProperty(entityData, variablePath);
        return String(variableValue ?? '');
    });
};

// Usage example:

const pathPattern = 'some/item/{path.to.id}/remove';
const entityData = {
    path: {
        to: {
            id: '123'
        }
    }
};

const renderedPath = renderPath(pathPattern, entityData);
console.log(renderedPath); // some/item/123/remove

ES5 example

The approach presented in the section uses typical JavaScript syntax.

// ONLINE-RUNNER:browser;

function getProperty(data, path) {
    var parts = path.split('.');
  	var result = data;
  	for (var i = 0; i < parts.length; ++i) {
      	result = result[parts[i]];
    }
    return result;
};

function renderPath(pathPattern, entityData) {
    return pathPattern.replace(/\{([\w.]+)\}/g, function(match, variablePath) {
        const variableValue = getProperty(entityData, variablePath);
        return String(variableValue == null ? '' : variableValue);
    });
};

// Usage example:

var pathPattern = 'some/item/{path.to.id}/remove';
var entityData = {
    path: {
        to: {
            id: '123'
        }
    }
};

var renderedPath = renderPath(pathPattern, entityData);
console.log(renderedPath); // some/item/123/remove

Alternative titles

  1. JavaScript - render path variables
  2. JavaScript - put variable into path
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join