Home » excel » Regex in Javascript to match the format of the SUM function in Excel

Regex in Javascript to match the format of the SUM function in Excel

Posted by: admin May 14, 2020 Leave a comment


I’m having trouble formatting my Regex expression in Javascript to test if the value in a textbox matches a similar format to that which you see in Excel.

So far I have this:

var equation = document.getElementById('functionBox').value;
var patt = new RegExp("=SUM\(.*\)");
if (patt.test(equation))
   //Continue operations

By my understanding, this SHOULD equate to only allowing the formatting of “=SUM()”, yet it passes as true if you remove either or both brackets and even removing the M in SUM before returning false.

Is there something I’m missing here or should I look elsewhere in my code to find the problem.

Also, I am aware at the moment that this will not take into account the formatting for the cells I but between the brackets; that I’m afraid I have no idea of accomplishing, and most Regex I try to Google for examples are either very specific, or just list off the modifiers without giving any examples to go along with them.

How to&Answers:

Since you’re using a string, you have to double-escape your parentheses:

var patt = new RegExp("=SUM\(.*\)");

For legibility’s sake (and many more reasons), use a literal regex:

 var patt = /=SUM\(.*\)/;

P.S. You can optimize this regex by using a negated group:

var patt = /=SUM\([^\)]*\)/;