JSFiddle - React, Tailwind, and code Playground
HTML
Matching http://c.tile.osm.org/24/7881145/7385476.png"
<br/>
with http://{s}.tile.osm.org/{z}/{y}/{x}.png
<br/>
<b>Result</b>: <script>document.write(JSON.stringify(r));</script>
JavaScript
function extractToken(template, tokenMapping, url) {
var tokenList = [],
regexpTemplate = template.replace(/\./g, '\\.');
// Find the order of your tokens
var i, tokenIndex, tokenEntry;
for (var m in tokenMapping) {
tokenIndex = template.indexOf(m);
// Token found
if (tokenIndex > -1) {
regexpTemplate = regexpTemplate.replace(m, '(' + tokenMapping[m] + ')');
tokenEntry = {
index: tokenIndex,
token: m
};
for (i = 0; i < tokenList.length && tokenList[i].index < tokenIndex; i++);
// Insert it at index i
if (i < tokenList.length) {
tokenList.splice(i, 0, tokenEntry);
}
// Or push it at the end
else {
tokenList.push(tokenEntry);
}
}
}
regexpTemplate = regexpTemplate.replace(/\{[^{}]+\}/g, '.*');
var match = new RegExp(regexpTemplate).exec(url),
result = null;
if (match) {
result = {};
// Find your token entry
for (i = 0; i < tokenList.length; i++) {
result[tokenList[i].token] = match[i + 1];
}
}
return result;
}
var sReg = '[A-z]',
xyzReg = '[0-9]+',
tokenMapping = {
'{z}': xyzReg
};
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myTemplate = "http://{s}.tile.osm.org/{z}/{y}/{x}.png";
r = extractToken(myTemplate, tokenMapping, myString);