Languages
[Edit]
EN

JavaScript - fill path pattern with path variables

10 points
Created by:
AnnLen
8880

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join