Search code examples
javascriptregexword-wrap

Break a long regular expression into several lines in JavaScript


I want to break the following regular expression into several lines of code.

document.body.innerHTML = document.body.innerHTML.replace(/Aarau|Aargau| <break here> more|words|follow|here/g, function(m) {
  return '<span style="background-color:lightblue">'+m+'</span>';
});

Solution

  • Here is an easy way to break the line:

    document.body.innerHTML = document.body.innerHTML.replace(
        /Aarau|Aargau|more|words|follow|here/g,
        function (m) {
          return '<span style="background-color:lightblue">'+m+'</span>';
        }
    );
    

    If you have a really long regular expression, write it as a string and compile it:

    var longRegex = new RegExp('Aarau|Aargau|aardvark|aardwolf|' +
        'aargh|more|stuff|earth|worm|earthworm|geese|moose|mice|' +
        'yet|more|and|more|et|cetera|and|so|on', 'g');
    
    document.body.innerHTML = document.body.innerHTML.replace(longRegex,
        function (m) {
          return '<span style="background-color:lightblue">'+m+'</span>';
        }
    );
    

    One more possibility is to write the individual words in an array, then join them with | when you compile the regular expression. This is especially convenient if you're already storing a word array.

    var words = ['Aarau', 'Aargau', 'aardvark', 'aardwolf', 'aargh',
        'more', 'stuff', 'earth', 'worm', 'earthworm', 'geese', 'moose', 'mice',
        'yet', 'more', 'and', 'more', 'et', 'cetera', 'and', 'so', 'on'];
    
    var wordRegex = new RegExp(words.join('|'), 'g');
    document.body.innerHTML = document.body.innerHTML.replace(wordRegex,
        function (m) {
          return '<span style="background-color:lightblue">'+m+'</span>';
        }
    );
    There is an aardwolf eating earth containing worms in Aargau.