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(z);</script>
<hr/>
Matching //tiles.arcgis.com/tiles/c/arcgis/rest/services/TimeZones/MapServer/tile/223774/24/2636"<br/>
with //tiles.arcgis.com/tiles/{s}/arcgis/rest/services/TimeZones/MapServer/tile/{x}/{z}/{y}
<br/>
<b>Result</b>: <script>document.write(z2);</script>
JavaScript
function extractToken(template, url, token) {
var sReg = '[A-z]',
xyzReg = '[0-9]+',
tokenMapping = {
'{s}': sReg,
'{x}': xyzReg,
'{y}': xyzReg,
'{z}': xyzReg
},
tokenList = [];
var regexpTemplate = template.replace('.', '\\.');
// 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);
}
}
}
var match = new RegExp(regexpTemplate).exec(url);
// Find your token entry
for (i = 0; i < tokenList.length; i++) {
if (tokenList[i].token === token) {
return match[i + 1];
}
}
return null;
}
var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myTemplate = "http://{s}.tile.osm.org/{z}/{y}/{x}.png";
var myString2 = "//tiles.arcgis.com/tiles/c/arcgis/rest/services/TimeZones/MapServer/tile/223774/24/2636";
var myTemplate2 = "//tiles.arcgis.com/tiles/{s}/arcgis/rest/services/TimeZones/MapServer/tile/{x}/{z}/{y}";
z = extractToken(myTemplate, myString, '{z}');
z2 = extractToken(myTemplate, myString, '{z}');