Tuesday, April 2, 2013

Regex Replacement String Math

I needed a simple method to do math within a regex replacement. Basically, a simple way for someone using a plugin to choose between a zero or one based index.

Yes, I could have just added an additional replacement like this:
var string = '&index0={index}&index1={index+1}'
  .replace(/\{index\}/, index)
  .replace(/\{index\+1\}/, index + 1);


That works! But what you if for some unknown reason needed the index to start at 2, 3 or even 10? Easy, go back in and modify the code.

Or, just use some regex math that allows you to set any number. Try this demo, and change the last input string to use "{index+10}" or even "{index-5}":

The code isn't really that complicated:
var string = '&index0={index}&index1={index+1}'
  .replace(/\{index([-+]\d+)?\}/g, function(fullstring, match){
    return index + (match ? parseInt(match, 10) : 0);
  });
It uses a replace function to take the index and add the first regex matching string obtained from the match argument.

But before that, we need to use a ternary operator to check if there is a match. If there isn't one, then add zero to the index.

We then need to parse the matched string into a numerical value so we can add it to the index. Then return the result.

I hope someone finds this useful :)

Wednesday, January 30, 2013

More fun with the base tag!

I have a post from a few years ago about using the base tag for debugging. Well I just figured out an even cooler way to use it in jsFiddle demos!

I have a base jsFiddle demo for just about every plugin I've made. It makes it easier for others to experiment with all of the plugin options to get a better feel for it. Well, at least I think so. At the very least, it makes it easier for me to build a demo to help all of you ;)

Anyway, I wanted to link to the images from the AnythingSlider github repo. The urls end up being quite long: http://css-tricks.github.com/AnythingSlider/demos/images/slide-civil-1.jpg

Enter the base tag! I just add it to the top of the html frame, and BAM short url sweetness inside :P



I tried making this same demo with codepen.io, but sadly it didn't work =(
Update 1/18/2014: It works on codepen.io now!