Building regexps in javascript

Let’s say you want to put together a JavaScript RegExp wherein you want, or need, to put together multiple strings or regexps then here’s the short version to get you on your way:

var re = new RegExp("some string" + /some.*(re)/.source);
"some string some        re".match(re);

Here’s a longer example showing a more in-depth and possibly practical example:

In this example let’s say you have something like an HTML table whose rows contain some information that you need to parse out, like ids,

var _ = require('underscore');

function Table(rows, options){
    if (!(this instanceof Table)){
        return new Table(rows, options);

    var self = this;

    self.rows = rows;
    self.options = options;

    self._id_for_row = function(row){
        var re = new RegExp(self.options.field_name + /_(\d+)/.source);
        return row.match(re)[1];

    self.row_ids = function(){
        return, self._id_for_row);

var table = new Table(
    ["user_name_field_1", "user_name_field_22", "user_name_field_23"],

# > console.log(table.row_ids());
# => [ '1', '22', '23' ]

Follow me on Twitter to keep up with what I’ve learned building my personal finance tool, Stash.

Subscribe to my mailing list to learn more about technology and business.

Your email will never be shared with anyone else.

Read more posts …
Written: January 5th, 2012
Categories: javascript, regexp, regular-expressions