简体   繁体   中英

javascript regex string template extract variable

I'm doing kind of a reverse templating thing, I have a string, and I know the template used to generate it, I want to get the variable value.

For example: URL: http://c.tile.osm.org/24/7881145/7385476.png

Template: http://{s}.tile.osm.org/{z}/{x}/{y}.png

I would like to get the zoom level ( {z} ) from the tile's URL, in this case 24. This exact Template url will not always be used (it varies based on what basemap is used, etc.), but I'll always be looking for the {z} value.

You can capture values using a regex. This thread is similar to your case, and here would be your solution:

var myString = "http://c.tile.osm.org/24/7881145/7385476.png";
var myRegexp = /http:\/\/[A-z]\.tile\.osm\.org\/([0-9]+)\/([0-9]+)\/([0-9]+)\.png/;
var match = myRegexp.exec(myString);
alert(match[1]);  // 24

And here's the fiddle: http://jsfiddle.net/2sx4t/

EDIT :

Following to your comment, here's the most flexible code I could quickly provide you: http://jsfiddle.net/2sx4t/4/

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}";

var z = extractToken(myTemplate, myString, '{z}');
alert(z);  // 24

var z2 = extractToken(myTemplate, myString, '{z}');
alert(z2); // 24

The tricks in this code is the combination of the use of template.indexOf(m) to be able to find the order of your tokens and String.replace() to generate the appropriate RegExp .

Note that I shuffled the order of the tokens in myTemplate2 and that it sill works.

Don't expect magic from RegExp , magic is in our brains ;-)

Bonus with map return, independantly of other tokens: http://jsfiddle.net/2sx4t/8/

It looks like blint may have beat me to it, but essentially what you want to do is generate a regular expression from your template and execute it:

function zFromTemplate(str, template) {      
  var sr = template.replace("?", "\\?")
    .replace(/\{[^z]\}/g, ".*?")
    .replace(/\{z\}/g, "(.+)");

  var rex = new RegExp(sr),
      parts = rex.exec(str);

  if(parts) {
    return parts[1];
  }
  return null;
}

And here's a codepen demonstrating it's use . If nothing else it's a little more succinct than the originally accepted answer.

Well, if you're sure that the {z} parameter is the only 1 or 2 digits element in your URL, you can try with regexp:

var myRegexp = /.*\/([0-9]{1,2})\/.*/;

This would match the last occurrence of any one or two digits enclosed in two slashes (/1/, /24/, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM