JSFiddle - React, Tailwind, and code Playground
JavaScript
var subObject = {
id: "world",
gallery_id: 522,
bitch:"eereresss"
};
var text = '/test/:name/:place';
text = '/gallery/:id(/:gallery_id)';
var replace = function(str, object) {
str = str.replace(/:(\w+)/g, function(match, group) {
if (group in object && typeof object[group] === 'string' || typeof object[group] === 'number') {
let val = object[group];
delete(object[group]);
return val;
}
return match;
});
//Any optional parameters present? Check for the existance of a bracket
if (str.indexOf('(') !== -1) {
//Remove unused optional parameters
str = str.replace(/\(\/:(.*?)\)/g, ''); //Todo: improve this regex? It only matches (/:xxx) currently
//Remove brackets from any filled optional parameters
str = str.replace(/\(|\)/g, '');
}
if (str.indexOf(':') !== -1) {
console.log('Invalid URL, not all parameters present');
}
return str;
};
var replacedText = replace(text, subObject);
alert(replacedText);
console.log(subObject);