${post.fImageName}

Fluid layouts done right, with Flexbox

How it used to be

Did any of you develop in the era of using tables for position and structuring your design? It worked, and we got pretty good at it. But it bloated our markup, was overly complicated, and very wrong in regards of semantics and accessibility. It basically got the job done, but nothing more than that. It did everything else wrong.

With the magic of float:left and float:right we could do the same as we did with tables. We were saved! Or so we thought. After transitioning from tables to floats we still missed a lot of the benefits the table elements gave us. Things like equal height columns, and vertical alignment, proved to be something other than a walk in the park when it came to floating.

Floating divs and other elements is more correct semantically, because the style and layout is moved to your stylesheet. It’s more accessible. But for the developer it got a bit too tricky sometimes, as mentioned. A plethora of CSS-hacks, tricks, and quirks, popped up. To do simple things like fixed footer and equal column height you had to think outside the box; switching out display: inline to display: table-cell, wrapping things in extra elements, adjust positioning, faking things, and so on.

What is the flexible box model

The flexible box model is like the other box models. It has content, padding, margin, border, and outline. It works on the semantic you usually use, like the good old div, or the new guys in town: article, aside, header, etc.

When you in your CSS say that an element is of the flexible box model type, that element starts to get almost super powers. As the name implies this models main advantage is its flexible nature. Everything inside a flexbox will be treated as flex children. These kids can easily and dynamically take the same height as the other kids, add liquid space between them, occupy all the space that is available after another element took X pixels, vertical align any block, reorder the visual presentation apart from the semantic one, etc.

By setting display: flex; on your wrapping element, you now have a completely different way of working with positioning and layout. You don’t even need to set margins on these kids because the flexible box model supports dynamic justify, like space-between that just adds space between the elements from the available unused space.

How is flexbox better?

Working with the web has always been perhaps a more growing and evolving business than others. As we advanced in the field of design and UX, we found existing techniques and used/combined them to produce what we needed. As was the case with Tables, a markup not meant for design. Then came floats, which was more meant for design. But as our designs kept evolving even floats started to fail us.

Flexbox is more or less architected from the ground up to actually be the supreme solver of all things positioning and flexibility. With a “tool” that’s from the ground up made to solve all these things, we get a code that is much easier to maintain, more readable, less dependent, and more future proof. During the transition period we will of course have a lot of people that haven’t learned flexbox yet, but in the past we’ve seen the community taking a big part in educating the masses.

We can’t but applaud the fact that we can potentially drop a few JS-plugins and polyfills as flexbox gets better support. And our semantics and the logic of our stylesheet improve. Equal height on divs (columns) - no problem. Reorder DOM-elements when displaying them - no problem. Vertical alignment - no problem. Sticky footer - no problem. Not all of them need extra JS, but we need to produce extra CSS to get it working, and adding more to our code at a later stage might turn really ugly.

However, no matter how sweet this new technology is, we do have to wrestle the ever present browser compatibility issues. But on the bright side, conformance to W3C-standard is pretty high for flexbox in most modern browsers, and non-supporting browsers see a steady decrease on its user base.

Check out html5rocks.com for more information on flexbox performance.

Browser compatibility

Something that’s a bit unique with the flexbox-standard is that it has been implemented twice. We had an intermediate implementation in most modern browsers, during flexbox working draft stage at W3C. And two years later the working draft became candidate recommendation, with major changes to the standard. So, the browsers implemented it all over again, leaving the developers with two different supports for flexbox - yeey!

Other than that, Chrome, Firefox, and Opera have had good support for some time now (from 2012). With IE catching up with the support in their 11th version. IE10 supports its own hybrid between the new standard and the old one. And older browsers (Firefox, Opera and Webkit-based ones) support either the old standard (post 2009), or none (pre 2009). Of course some with vendor prefixes sprinkled over the code based on browser modell.

Check out Can I Use for more on browser compatibility as it’s kind of a big mess. For modern browsers you should get a long way using flexbox standard syntax with the -webkit- vendor prefix added in. flex-wrap and flex-flow (flow is just a short-hand for many other flex-commands that do work) will give you the most problems, since they’re not supported in modern Firefox (as of January 2014). And if IE8 and IE9 are important to you, you’re kind of out of luck. But a polyfill called Flexie JS can be used to make the old 2009-syntax work on older browsers. For the modern standard, the world has yet to invent a polyfill.

If you are eager to start using flexbox now, you can try FlexboxDetective developed here at Enonic. It lets you target browsers with flexbox support by adding classes to the html-element. This way you can provide fallbacks for older browsers. Much like how Modernizer works, just slimmed down as much as possible to just check different kind of Flexbox support.

Examples

Fixed and fluid width columns

flex-grow, flex-shrink and flex-auto determine how to fill the remaining space along the main axis.

fluid1.png
Fixed width columns - 1
fluid2.png
Fixed width columns - 2

To be replaced

To be replaced

Although all items have width set to 100px, only the three first items will be flexible. The last item has both flex-grow and flex-shrink set to 0.

Equal height

By setting item-align to stretch, we tell the flex items to all take the height of the tallest item in the same row. Note that height, min-height and max-height are still respected. Item two is still shorter than the other items since height is set to 120px. 

equal-height.png
Equal height example

To be replaced

Advanced example

In Flexboxshopping (jsbin) we have used flexbox to do several things:

  • The header, nav, main and footer element are all flex items with flex-direction set to column.
  • The menu is flexbox.
  • Flexbox is used to give the right column the same height as the element wrapping all the products. The right column also has a fixed width while the product wrapper fills the rest of the width.
  • All the products are flex items with min-width and max-width.
  • The elements inside the product box are flex items. This lets us align the “More information” link to the bottom.

Tip: Try resizing the example to experience flexbox in action.

Note: This example will not work properly in browsers that don’t support the flex-wrap property (Firefox 27 and below). For browsers who don’t support flexbox it will obviously not work at all.

Flexbox CSS properties

The flexible box model uses various properties to control the layout with a containing element and its child elements. Some of the CSS properties are applied to the flex container and others to the flex items.

Flex container properties

display: flex | inline-flex;

A flex container is defined with the display property.  Using the value inline-flex causes the container itself to be rendered inline, and using flex will render the container as a block element. CSS columns do not have any effect on a flex container.

flex-direction: row | row-reverse | column | column-reverse;

The default value is row which will align the flex items horizontally, ordered left to right while column will arrange them vertically, top to bottom. Using either of the reverse values will simply change the order in case you ever need right-to-left or bottom-to-top. When the main axis of the container is horizontal, the cross axis is vertical. The flex-direction determines how many of the other flex properties behave, so the following examples will assume the default horizontal axis unless stated otherwise.

flex-wrap: nowrap | wrap | wrap-reverse;

The default here is nowrap which will place the flex items in a single line. If set to wrap then flex items will wrap to the next line along the cross axis. This does not yet work in Firefox so don’t plan on using multi-line any time soon.

flex-flow: [flex-direction] || [flex-wrap];

This is the shorthand way of setting flex-direction and flex-wrap in the same line of CSS.

justify-content: flex-start | flex-end | center | space-between | space-around

This defines how flex items will be aligned along the main axis. The default is flex-start, so when the main axis is horizontal, the flex items will start on the left. Using flex-end will align the items to the right and center will center them. Using space-between will put an equal amount of space between the flex items and space-around will put space between each item. Of course this is only useful when the combined width of the flex items is less than the width of the container.

align-items: flex-start | flex-end | center | baseline | stretch

This is very similar to the justify-content property but for the cross axis. When the main axis is horizontal, the flex-start and flex-end values will align flex items with the top or bottom of the container respectively. Using center will align them in the middle and baseline aligns them according to the text baseline. The default is stretch, which will make all the flex items the same height as the container unless they have a height or max-height specified.

align-content: flex-start | flex-end | center | space-between | space-around | stretch

This is pretty much the same as justify-content except that it works on the cross axis and only when there is more than one line of flex items.

Flex item properties

The properties float, clear and vertical-align have no effect on flex items.

order: [integer]

If you want to change the default document order of your flex items, simply specify the position by number.

flex-grow: [number]

The number value specifies the proportion that this flex item should grow to take up available space in the container. The default is 0 so this won’t take up extra space. If each flex item has this set to 1 then they will all be the same height as the tallest. If one is set to 3 and the others are set to 1 then that flex item will be three times taller. Of course flex-grow will affect the width rather than height when the main axis is vertical.

flex-shrink: [number]

This is the opposite of grow. The default is 1.

flex-basis: [length] | auto

The default size of a flex item can be specified before the remaining space is distributed. The default is auto.

flex: none | [flex-grow, flex-shrink, flex-basis];

This is shorthand for flex-grow, flex-shrink, and flex-basis. Only the first parameter is required and the default is 0 1 auto.

align-self: auto | flex-start | flex-end | center | baseline | stretch;

This is for aligning individual flex items and overrides the align-items property.

In a world of darkness, where no CSS standard ruled the world – one man had one destiny: To kill all nasty CSS hacks. Having defeated tables in an epic battle with divs, our hero witnessed a new enemy rise from the ashes. Known as floats, this ruthless enemy left a flaming trail of devastation whenever the people called upon him. But our hero had a secret weapon: the weapon of flex.

Continue reading »

${post.fImageName}

Animate your webpage with the scrollbar

What is Skrollr

Skrollr is a JavaScript-plugin that helps you animate objects on your webpage as you scroll. A lot of people call it "Parallaxing", but that is just one of many effects you can add to your site. There are plenty of these kind of plugins out there, but from my light testing I found Skrollr to be the most lightweight and straight-to-the point of what I needed.

You just include Skrollr and then append data-attributes in your HTML, this will create animation keypoints at different scroll positions. Then tweak your animations with normal CSS-styles while Skrollr works the magic. It doesn’t even need jQuery, so it’s a very quick load.

However, I’ve found Skrollr - as well as many other plugins - totally missing a "Getting started guide". So you’re kind of left at looking up the source to get started, or digging through the source of some examples, and that is absolutely not for everyone. I thought this guide might help you get started with it, with some basic setup and examples. It really is very simple!

To see a demo of some of the possibilities we have with Skrollr, check this link:

http://prinzhorn.github.io/skrollr/

Download and "Install"

First things first. Let’s download Skrollr, which isn’t such an intuitive task that you might think. Mainly because there is no download. You have to go to the projects Github-page, and then find the correct minified JavaScript-file, then select all code and manually create this file on your own with that code.

The latest files on Github are also not the greatest as they're work in progress. So find version 0.5.14, which is the stable release this text was based upon. You can find a link to the correct version in the projects main readme-file.

Now open up the "Dist"-folder, and then open the first file in there - " skrollr.min.js ". There you go! Just place it with your HTML and CSS-files and include it the bottom of your page.

Starting up

Create the basic structure of this test case in a folder on your computer. Let’s call it "skrollr". Create a "index.html" in there, and a "style.css". You also need to place the minified Skrollr-code in there. You are of course free to name and place the files wherever you’d like, but my example code will use this structure.

Open your newly created html-file and paste this basic structure in. The only important parts are that you include Skrollr and a CSS-file. But let this serve as a quick start:

https://gist.github.com/Bellfalasch/937a4de6b14d271122d0

With this code you have all you need to start. We will place a few div-tags in here, and a init-script. And we will create some styles. But let’s get that init-script in place so Skrollr get’s loaded (adding the script-tag isn’t enough).

Just paste this small JavaScript init-snippet in the empty script-block near the end of your html-file.

// Start Skrollr
window.onload = function() {
    skrollr.init({
        forceHeight: false
    });
}

The line skrollr.init is the important one, surrounded by a simple onload-check so that we don’t start manipulating the DOM before it’s finalized. In this example we can see a setting being sent in with the init-setting, forceHeight, set to false. The default is true, so you could just remove the setting altogether if you’d like to change it. What forceHeight does is to make sure that if you try and animate something beyond the total height of your html body, Skrollr will force an increase on the height to allow you to enjoy the full animation. I just included this setting this time to show you how basic settings works, we don’t really need forceHeight for this example to work.

First basic demo

Almost done! Nah, not really. But let’s get going with things you already know - HTML and CSS. My idea for this example to get you up and running in a quick and easy enough way is to simple have three tall blocks stacked on top of each other that we’ll scroll by and see some kind of different animation on each of them.

https://gist.github.com/Bellfalasch/5a1fcbdd1e5e812a387c

With this markup (we will come back to the other examples/blocks later) we can move on to our CSS:

/* General */
body, html {
    height: 100%;
    padding: 0;
    margin: 0;
}
.block {
    height: 100%;
    box-sizing: border-box; /* One of my CSS3-favourites */
}

/* Specifics */
#block1 {
    background-color: black;
    color: white;
    padding: 20px;
}
    #block1 p {
        width: 200px;
        line-height: 200%;
        margin-top: 400px;
    }

We just give all the blocks some height, namely the height of your current viewport on the browser. We also force the body-tag to be at least one viewport tall. At last we give some simple style to the top block and it’s text, like color and spacing.

Now, if you take the html-page for a test spin, you should be able to see a big black block of fullscreen background, and some white text. Also make sure you get no weird errors.

But scrolling doesn’t do anything!? OMG! But don’t worry, you just need to write thousands of lines of JavaScript to move the p-tag ... Nah, just kidding. We just need two small attributes added to our html! I kid you not, check this out:

https://gist.github.com/Bellfalasch/232254f890c545c3bf1c

Save and retry, it should perform magic right before your eyes as you scroll downwards (and then reversing when you go back up again).

The data attributes are all that you need to add to trigger Skrollr. Skrollr will automagically animate any CSS you place between your start and stop positions.

data-start is the starting point of your entire page, the absolute top, your page’s y-axis = 0.

data-500-start is the end and triggers 500 pixels from the very top (start) of the page.

You could change this around to test and see how it works. Skrollr just animates your CSS from the closest to the top down to the furthest from the top - from padding-left:20px; to padding-left:400px; the more you scroll down the page.

Important to note is that you must specify some CSS in each data-attribute, Skrollr won’t read anything from your CSS-file.

Change this CSS around a bit to experiment with your animation. It’s really nice and easy. Almost no new syntax to learn and remember, isn’t that sweet?!

Onwards

Now you know the basics of how this works. Let’s do a couple of more examples which will introduce a few more Skrollr-goodies.

Next task is to animate multiple attributes, at the same time! And we will also stack two animations after another by adding more data-tags. Don’t sweat, this is also easy!

This time we will not manipulate anything on the main block, so create a new div inside of the "block2" div with these attributes:

https://gist.github.com/Bellfalasch/83d33fe47bf3fc13dc6d

That’s all! This will animate a 100x100 little red block up to 300x300, then slide it from the top of the containing block down 300 pixels - following the screen as it scrolls.

Let’s analyse this new code we’ve added:

data-top is new, but it behaves very similar to data-start with the difference that data-start fires at the absolute top of the document while data-top fires when the top of that specific block hits the top of the viewport.

data-600-top By specifying a number of pixels before the "top" setting we offset the start with that number of pixels. Here we start the animation 600 pixels before this object reaches the top of the current viewport.

You might have already figured this out, but data-600-top fires before data-300-top, which in turn fires before data-top. So it almost fires backwards to what you would expect, until you get used to this. Stringing many trigger-points together like this let’s you change the animation for the same object at many different scroll positions. You could add as many as you’d like, but try and not go totally nuts about it.

A more advanced example

Now let’s raise the bar even further for our final task. We’re gonna animate three different objects - at the same time, at different trigger points! One block will slide in from off-screen and then get larger, another will change color, and a third block of text will come sliding up from invisibility.

https://gist.github.com/Bellfalasch/f437d7cd32a98efddcec

I’m just assuming that you can figure out all of these animation steps, at least good enough so that nothing in there is confusing. The "hsla"-color is explained a bit more in the CSS, and you can look it up on - http://www.css3.info/preview/hsla/ - if you’re unfamiliar with it. Skrollr makes it very easy to animate color changes when we use the hsl(a) or rgb(a) syntax. Skrollr cannot animate color as strings, like "red" to "blue", or hex-values like "#000" to "#f3f904", so you need to get your hsl/rgb-skills straight right away.

Let’s do a few additions to the CSS-file before testing this out:

#block3 {
    background-color: #bbb;
}
    #block3 div {
        float: left;
        height: 50px;
    }
    #block3 div:nth-child(1) {
        width: 100px;
        margin-left:-400px;
        background-color: hsla(255,70%,100%,0.9);
        /* HSLA: Hue, Saturation%, Light%, Alpha (Opacity) */
    }
    #block3 div:nth-child(2) {
        width: 200px;
        background-color: hsla(200,70%,100%,0.1);
        border: 5px solid black;
    }
    #block3 p {
        padding-top: 400px;
        opacity: 0;
        width: 200px;
        line-height: 200%;
    }

Nothing extra fancy here, except the use of the CSS-selector nth-child to select the first div and the second div without giving them unnecessary id tags in the markup. And as I said before, if you’re not familiar with the hsla-coloring in CSS3 you should check that up. Basically, this CSS just gives some color and shape to the two blocks and the text. You should test the effects out.

What’s next?

There’s a lot more to test and learn with Skrollr, but now that I have got you started I leave that task to you. data-end, data-center, data-bottom, and data--100-top (for when a object is 100 pixels with it’s top above the viewport) are some other cool triggers you can try out. Also easing of animations - "padding[swing]:10px;" - should be checked out as there are a few methods to choose from.

And of course you shouldn’t miss trying to make your own parallaxing background-demo. Just add three divs, position them absolute on top of each other, make them cover the screen, set a PNG-background with a lot of transparency on each, then make them reposition these backgrounds with background position at different speeds (higher start-stop trigger difference = higher speed) as you scroll.

Be aware of

All is not all good in the world of scrolling and animations though. I’ve discovered that animating large images - especially with animated text on top of it - gives a very choppy experience. And with scroll-triggered animations, you must always keep in mind that the user can scroll very fast, or very slow, which drastically changes the experience. So scroll-triggered animation isn’t perfect for everything.

Also, when the page has loaded and Skrollr has initiated, it will take the first trigger-point for each object and apply that CSS as inline style. If your stylesheet differs from this, you will get a loading experience where the objects on the page looks like they hop around as the Skrollr-style overrides your stylesheet.

Skrollr has a special plugin for mobile, running normal Skrollr on mobile doesn’t work very well. However, Responsive animation takes some extra effort to get working smooth since most triggers use pixels. You can bypass that by only triggering animations on data-top and dynamic values like percentage. You could also create trigger objects in the markup that with their unique id value and the data-anchor-target helps trigger animations.

Reading more

For the offical documentation you should check this link: https://github.com/Prinzhorn/skrollr/tree/0.5.14#documentation

Some examples

The main example-page by the plugin author:
http://prinzhorn.github.io/skrollr/

A collection of different examples:
https://github.com/Prinzhorn/skrollr/tree/master/examples#examples

Article teaching you to animate images, including drawing along a SVG path:
http://pepsized.com/merry-scrolling-with-skrollr-js/

A Nettuts+ article about beginning with Skrollr:
http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/jazz-up-a-static-webpage-with-subtle-parallax/

Some pages that use Skrollr

Subtle effects to spice up an article:
http://futuremylove.com/#home

Heavy use of image-swapping to create 3D-like effects:
http://www.officeline.se/kampanj/
http://moto.oakley.com/

Entire source HTML

https://gist.github.com/Bellfalasch/7029de0eb4f40a547cdd

Entire source CSS

/* General */
body, html {
    height: 100%;
    padding: 0;
    margin: 0;
}

.block {
    height: 100%;
    box-sizing: border-box; /* One of my CSS3-favourites */
}

/* Specifics */
#block1 {
    background-color: black;
    color: white;
    padding: 20px;
}
    #block1 p {
        width: 200px;
        line-height: 200%;
        margin-top: 400px;
    }

#block3 {
    background-color: #bbb;
}
    #block3 div {
        float: left;
        height: 50px;
    }
    #block3 div:nth-child(1) {
        width: 100px;
        margin-left:-400px;
        background-color: hsla(255,70%,100%,0.9);
        /* HSLA: Hue, Saturation%, Light%, Alpha (Opacity) */
    }
    #block3 div:nth-child(2) {
        width: 200px;
        background-color: hsla(200,80%,100%,0.8);
        border: 5px solid black;
    }
    #block3 p {
        width: 200px;
        line-height: 200%;
    }

Entire source JavaScript

None needed - woop woop!

Ever scrolled down a website and been amazed that objects doesn't behave like you expect them to? Instead of flowing static content upwards on the screen as we scroll we can now easily animate them in any way. Fly text sideways, zoom in images, fade out objects, and more!

Continue reading »

${post.fImageName}

Internal server testing using BrowserStack

BrowserStack features

There are many browser and device testing services for webpages, but BrowserStack is one of the most powerful alternatives out there. First of all, you get to see how your webpage looks in practically every common browser and operating system version, including mobile platforms. But in addition to this, you even get a live view inside the virtual browser setup, including debugging tools. So in total, the features that BrowserStack comes with makes it invaluable as a testing tools for web developers.

But one of the challenges with using BrowserStack for testing internal web sites, is that the testing is performed remotely, which becomes a challenge when you're testing sites that have no public access. Previously, this was only possible to circumvent using an SSH tunnel, and depending on the environment, this could be a bit complicated to set up. But now there are browser extensions/add-ons available for Chrome and Firefox, so the process of testing internal web sites has become much simpler.

How to set up Local Testing

There is a very straightforward guide on BrowserStack.com telling you all the necessary steps. Here's a quick summary:

  1. Install either the Chrome extension or Firefox add-on
  2. Log in to BrowserStack and, click the large button for enabling Local Testing
  3. Specify your server address, for instance "http://localhost" and the port number (80 by default).
  4. Follow the resulting link that BrowserStack provides

In the situations where this setup does not work, you could also choose a local folder with HTML files on your hard drive to test.

Troubleshooting

Not every local installation is easily testable using the Local Testing feature, but there are workarounds:

error-message.png
Error message
  • Local network does not have access to the internet. To get around this problem, you can set up a proxy, and BrowserStack has some Command-Line tools that allow you to do this.
  • Password-protected sites. If you try connecting to a password-protected site that redirects to a login page, BrowserStack cannot connect automatically. The solution is simply to try the direct address to the login page, instead of the default front page or whatever resource you were trying to access.

With these points taken care of, the testing may commence!

When developing internal websites and using various QA environments, these are often isolated and not accessible from the public web, which can make browser and device testing very challenging. In these situations, BrowserStack and its Local Testing feature can be very helpful, and with the new browser extensions, this process has become very simple.

Continue reading »

${post.fImageName}

The basics of Regex explained

Learning Regex

On this years JavaZone I attended a talk by Rustam Mehmandarov about Regex. In this talk he broke down Regex into its smallest pieces and explained them all, one by one, with examples. He also went through a few bigger examples. So I'm gonna copy his style of thinking and do the same in this article. Thanks to his talk I began to understand - and actually remember - the fundamentals of Regex. I now understand it so good that I actually could write the last two examples from the top of my mind. And for me versus Regex that's the major breakthrough I've been waiting for.

Normal search

Just writing normal text in a Regex will perform a normal search.

Dan - Matches the word “Dan” in a string.
Hello - Matches the word “Hello” in a string.

But the true power of Regex comes when you start using all of its special features.

Square brackets [x]

Square brackets match something that you kind of don’t know about a string you’re looking for. If you are searching for a name in a string but you’re not sure of the exact name you could use instead of that letter a square bracket. Everything you put inside these brackets are alternatives in place of one character.

Some examples:

[D]an - Matches “Dan”, not very useful.
[DB]an - Matches “Dan” and “Ban” (first letter can be "D" or "B").
[DBTP]an - Matches “Dan”, “Ban”, “Tan”, and “Pan”.
Da[ng] - Matches “Dan” and “Dag” (last letter can be "n" or "g").
[Dan] - Matches single character “D”, or “a”, or “n”. Meaning it will not match the entire string "Dan", only one single character (probably not what you wanted).

You can have multiple brackets in one string, like so:

[DB]a[ng] - Matches “Dan” and “Ban”, and also “Dag” and “Bag”.

Ranges [x-x]

You can also advance your brackets with ranges. These are especially handy when we need to validate against the alphabet or numbers. You specify a range by writing the first character, followed by a dash, and ending with the last character. 

Some examples:

[A-Z]an - Match “Aan”, “Ban”, “Can”, “Dan”, and all the way up to “Zan”.
[A-C]an - Match “Aan”, “Ban” and “Can”.

We can make it more complex by adding more to our brackets. How about multiple ranges with mixed in single characters.

Some examples:

[AC-D]an - Match “Aan”, “Can” and “Dan”.
[A-CF-G]an - Match “Aan”, “Ban”, “Can”, “Fan” and “Gan”.
[A-BF-GZ]an - Match “Aan”, “Ban”, “Fan”, “Gan” and “Zan”.

The Regex looks at each letter like an alternative to match against except when you add the dash, then it understands that the two surrounding characters and everything between them will be matched.

Some examples:

[0-9]an - Match “0an”, “1an”, “2an”, “3an” and so on all the way to “9an”.
[0-9A-Z]an - Match any “an” starting with a number or capital letter.
[a-ZA-Z0-9]an - Match any “an” starting with any number, lower case or capital letter.

Not [^]

Brackets are powerful indeed. And this is just starting it. Maybe you only know what you don’t want.

[^D]an - Match anything that ends with "an" and starts with any character except "D", so “Dan” would not be valid, but "San", "Can" or "man" would.
[^DB]an - Same as above, but also “Ban” is one of the invalid matches.

None of these two examples would allow empty first character, "an" would thus not be valid.

These “not”-searches can also be used with multiple brackets, characters, and ranges.

[^DB]a[ng] - Match anything that ends with “an” or “ag”, but must not start with “D” or “B”.
[^D-G]an - Match anything *but* “Dan”, “Ean”, “Fan”, “Gan”, but "San" and "pan" is for example valid.

Hey this is not bad. You have now taught yourself about the square brackets, multiple alternatives in them, ranges, and the not-search.

Special characters .

It's not always handy to use brackets. The . (dot) placed outside of a bracket will work as the “anything”-character. It will match numbers, letters, question marks, and everything you can think of. 

.an - Match anything that starts with something and then ends with “an”, like “!an”, “7an”, “zan”, “Ran”, “_an” and “[an”. 

The dot only matches one single character (but any type of it). If you need you can use quantifiers with it (explained more in detail pretty soon). Like .*an would match any character, for zero or infinite amount of times, ending with an. A very wide search, most likely not that useful all the time.

Quantifiers *+?

So you might like the bracket-search you wrote earlier and want to re-use it for more than just one character. Then we can use quantifiers. Let’s say for popular example that you want to validate a western style first name (just letters, for simplicity). 

[a-z]* - Match anything with letters between “a” and “z” following each other, for zero or infinite amount of times.

The star/asterisk immediately behind the brackets means “find what I just typed any amount of times”. While [a-z] only would match “a”, “b”, etc [a-z]* matches “”, “a”, “aaa”, “kjh”, “dlfkajhsdflkajhd”, and everything you can monkey-type on your keyboards alphabetic keys. It will however also accept a completely empty string since * means “any amount”, thus also “zero”. 

[a-z]+ - Match anything with at least one letter between “a” and “z” following each other. 

The plus sign takes care of that empty string problem. It means - almost like the star - that we want to match any amount, but the difference is that it can’t be zero of it!

There’s also another small possibility to improve our Regex for finding names since it doesn’t take capital letters into account. So let’s fix that.

[A-Z][a-z]+ - Match words starting with a capital letter followed by at least another, small letter. 

This would therefor match things like “Da”, “Boo”, “Gaah”, and “Xksajhds”, but not “xmn”, “762”, “c”, or “” (empty string).

With the ? character we will match zero or one, but not more than that.

a[0-1]? - Match a string being “a”, or “a0” and “a1” but never “a11” as that was too many occurrences of the number.

Quantifier summary

Let's recap the basics of quantifiers:

? = Match zero or one occurrences only.
+ = Match infinite occurrences of a character but never zero occurrences.
* = Match zero, one or infinite occurrences.

Quantifiers, part 2 {x}

But, what if you know the exact amount of times this bracket-match should occur? Like when looking for Norwegian zip-codes (always four digits). In that case we can’t use the special * or + but have to set the number explicitly.

Some examples:

[0-9]{4} - Match any number for exactly four times in a row.
[0-9]{1} - Match any number for exactly one time (same as writing [0-9]).
[12][0-9]{2} - Match anything starting with a “1” or a “2” followed by exactly two more numbers between 0 and 9.

But, what if we want to find a year in a string. A year can be written with two or four digits. Can we do that with Regex? Of course!

Example:

[0-9]{2,4} - Match exactly two or exactly four numbers following each other. So “99” is as valid as “1999”.

With the comma we can define more than one quantifier for that match. Thus covering almost any example of matching we can come up with.

So as you can see with brackets, the dot, and the quantifiers we can do pretty cool things. And this is still just the beginning.

More special characters ^$

Used outside of the square brackets the ^ and $ sign will have new meanings. And yes, this is a big part of why Regex is a bit confusing to start up with. Instead of the ^ meaning “not these characters” it means “start of the string”.

Let’s see the difference with two examples:

[0-2]+ - This will match any occurrences of at least one of “0”, “1”, or “2” starting anywhere in the string.
^[0-2]+ - This does the same as the above, except the ^ characters tells the Regex that the match must be at the very start of your string. It would thus match “12hi”, “2goodbye”, “0” but not “hi0”, “cheers 012” or “one 2 three” (which the first one would’ve matched).

Very much like the start-of-string character we have an end-of-string character: $

It’s used in the end of your Regex to signify that we match for the end of our string. If used together they would mean that only what you search for is allowed in that string, nothing else.

^[0-2]$ - Match only strings being “0”, “1”, or “2” without any other text.

Grouping (x)

All these matches you get doesn’t mean much if you need to find a specific text and extract it, or replace it. The previous examples would work fine for validation of data, if the Regex finds your “search” it will return true and thus validating the string. But, you will get even more out of Regex when you start doing replacements in strings, and to do that you need to store your matches in memory. And you do this by wrapping parts of your Regex in parentheses. In Regex this is called grouping.

(hej) - Match the string “hej” and store it in memory.
(hej|hei) - Match the string “hej” or “hei”, and store it in memory.

Use them with special characters:

test(.*)r - Match any string that starts with “test”, ends with “r”, and stores whatever it finds between (using the any-character for any amount of times), be it "" (empty string), “a”, or “osterone”, etc.

Use them with square brackets:

age ([0-9]*) - Match “age “ in string and any following numbers, storing the numbers.

Only use parentheses for things you need to access later.

Dissecting examples

Well I could go on explaining more and more about all things Regex that I've learnt from Rustam's presentation. But I’ll end now with two real-world examples, going through every little part of it.

[\/?&]test=([^&#]*)

The what now!? So let’s just take this slow. 

[\/?&]

First we have the square brackets, this means that we will start at something matching what's inside them. The two first characters are only one, as the first one is the escape character escaping the second one - a forward slash. We want to find things that start with an / but since writing just [/?&] would use the special functionality of the / character, we'll escape it first with the \ (backslash).

So basically, find something that starts with a "/", "?" or "&".

After that we see test= which basically just finds a normal text inside what we are searching. We will thus so far match on “/test=”, “&test=” and “?test=”. Maybe you can figure out that we want to analyse a URL. But what about the last part, that looks crazy.

([^&#]*)

First off, the parentheses are for grouping and remembering what is found. So the Regex-code inside here will find something and store it in memory so we can use it in some way. If we just remove the parentheses for clarity:

[^&#]*

The ^ meant “Not”. So it will not match any character that is the “&” or the “#”. You see how we by starting with an ^ negate all the following characters.

So we will match any characters that is not a "&" or a "#", for infinite amount of characters (even zero/space) - the asterisk, remember. What happens here is that what will be stored in the group is what comes after the “test=” until the string ends, or we come to a "&" or "#".

This Regex finds the QueryString “test” in a URL and stores its content. So if I used the URL example.com/page?test=hello I would have stored "hello" with this Regex.

One more example before I let you go:

^([0-9]{2})\.([0-9]{2})\.([0-9]{4})$

Let’s break it apart and add some spaces (always recommended since it makes it more readable and easier to understand in my opinion).

^
( [ 0 - 9 ] { 2 } )
\.
( [ 0 - 9 ] { 2 } )
\.
( [ 0 - 9 ] { 4 } )
$

Let’s start with the first line. It means “start of string”, so this makes sure that what we will match comes already on the start of the line in the string and not just anywhere inside the string.

At the end we have the $ character, matching for the “end of string”. So it looks for everything between it being on a line of its own. So our matching code is the only thing allowed on the line that we will get matches on.

([0-9]{2})

I guess this is somewhat easy to dissect now. First [0-9]{2} means any number exactly two times. Remember? And with the parentheses surrounding it we’ll store that match in a separate place in memory.

\.

After that you’ll see this. Remember . was a special character meaning “any character”. But here we really only want to match the normal dot character, as used to end sentences etc, and not any character. To do that we need to escape it with the backslash. Backslash is the escape character in Regex.

([0-9]{2})\.

Now we see the pattern repeating, we’ll match and store in memory another set of two numbers. Followed by a dot.

([0-9]{4})$

It all ends with a match for a set of four numbers. Then that line should end.

This gives us a Regex that will find any date formated as a Norwegian date (DD.MM.YYYY). Each part of that date is stored on its own in the memory so if we used this in for instance JavaScript we could access what we stored as an array and then reformat that string! Pretty cool huh!? But that is not covered in this little introduction.

NB! Important to note is that this Regex example is very basic and it will allow a huge amount of invalid dates, like 99 of June in the year 9999, or day 12 of the 79th month in the year 0000, etc. But writing the perfect Regex for dates would make for a pretty over complicated example.

Closing words

That's it for now. If you find this interesting, please comment, I might go for a follow-up article. Also if you have questions or need clarifications just ask.

A very powerful and visual tool for helping you understand Regex better is Regex101. Just paste your Regex there and to the right you'll see an explanation that breaks down your Regex into the smallest possible pieces. I've found this tool extremely helpful when the Regex is a bit too complicated to interpret by hand.

My relationship to Regex (or Regexp) has always been of the type "google it, copy and paste it, don't change it, never look back again". But so, finally, after years of eating that same old "copy pasta" I went on this talk about Regex on JavaZone and actually began to understand it. And now I'll share this introduction with you.

Continue reading »