[Tutorial] Implement Parenthesis Multiplication Using JavaScript & Regex

When learning a new programming language, a calculator is a great way to flex your ability. Going the extra mile and tacking on extra features proves to be an even more valuable experience. In this article, I will show you how to implement a neat feature: the ability to multiply without an * operator.

The case

A calculator can easily interpret input using the eval() function.

NOTE: For a simple calculator or for practice, using eval can make things easier. However, never use eval in production applications. Here’s a thread on the security risks of using eval in production applications.

6+7
6+(6–99/3)
6*99–100

Eval will interpret all of these inputs as code, then return and display the result. All is well and good.

However, some users may want to use parenthesis multiplication.

6(7)
10(5*70)

When eval interprets this as code, it thinks we’re trying to call a function.

Uncaught TypeError: 6 is not a function
Uh oh!

Eval, however, can successfully interpret 6*(7), which is the same concept as 6(7). Our app needs to take this input, convert it to eval friendly form, and return it back to the eval function.

You can view a working demo here.

For this job, we’ll write a function in Javascript.

function convertSigns: (text) => {
    return text;
}

For the first step, let’s identify where the * operator goes. It needs to prepend before the first open parenthesis.

The RegExp

A regular expression will do.

/\d+\(\d+\)/ will match the a typical multiplication case.

I know regexps can look daunting, bear with me.

For a refresher, \d matches a digit, with the + matching any number of times.

\( matches a literal parenthesis. The literal match is caused by the preceding backslash.

The Regex can be viewed as / \d+ \( \d+ \) /.

Match any number of digits, match a literal ‘(‘, match any amount of digits again, match a literal ‘)’.

Cool, so now we’ve matched the correct string. Our next task is to prepend that match with a *.

Replacing The String

To do this, str.replace will work just fine. However, we don’t actually want to replace the string. We simply need to interject a single character before a part of the string.

str.replace has an option to take a callback as a parameter.

text.replace(/\d+\(\d+\)/, (data) => {
    text = data.replace(“(“, “*(“);
});

We need a callback since we actually want to match part of a match.

Sounds confusing, I know. Just imagine we had a string that looked like ‘6(6)‘. From there, we could do something like:

str.replace('(', '*('); // 6*(6)
That’s essentially what we’re doing, but we don’t have that string initially. We have to first match it, then perform the replace on the result. That’s the beauty of the str.replace callback.

To sum it up: text.replace finds the correct match, then performs another replace on that matched string.

As a result, we can match the correct string without any interference with different types of input.

To match multiple instances, add a g flag at the end of your regex. This will match every instance of the string it finds, not just the first(default).

Now, let’s see the entire function!

convertSigns: (text) => {
    let multiplyRegex = /\d+\(\d+\)/g;

    //take the found string
    text.replace(multiplyRegex, (data)=>{
        //prepend a multiplication operator
        text = data.replace(“(“, “*(“);
    });

    //return for eval
    return text;
}

Now you can do something like:

let converted = convertSigns(“6(99)”);
eval(converted); //evaluates the returned output

Conclusion

This short and sweet tutorial shows you how to use simple javascript to successfully parse simple strings. Though, there’s so much more you can do!

For example, what if we need to interpret parenthesis inside of a pair of parenthesis. Something like 9(9+8(9)). It’s definitely doable with a little JS magic. Have fun!

Leave a Comment

One Comment