How to Make a Calculator Snippet with Javascript in TextExpander

Maia Olson Blog, TextExpander, TextExpander Tips

Thanks to the magic of JavaScript snippets, you can make a snippet which acts as a calculator. TextExpander’s ability to execute JavaScript at the time of snippet expansion is one of the features which makes it so powerful. Here is how you can use some of that power in your own snippets.

Create a new snippet from the button in the app menubar, and give it a Content type of JavaScript. For this example give it an abbreviation of =\, though the abbreviation can be whatever you want.

Now paste in the following content:

"" + (%filltext:name=calculation:width=40%) ;

Here’s what it looks like in TextExpander’s snippet editor:

Calculator Snippet

Now, with your complete snippet, give it a try.

Type the abbreviation =\ in whichever app you like for your typing. A form for entering your calculation will pop up. To add 2 plus 2 in the form type, 2 + 2. Here’s what that would look like:

Calculator Form

Press OK, and 4 will appear where you typed your abbreviation!

How does it work?

Well, the %filltext in parentheses above effectively gets replaced by what you type. So, when you enter 2+2, JavaScript executes: "" + (2+2);. Adding to an empty string in JavaScript converts the remainder of the statement to a string, so we end up with a result of “4”.

Learn More

If you want to learn more about scripting in TextExpander, check out the Scripts section of our Tips page.

If you have cool scripts you use, let us know on Twitter or Facebook, we love learning new ways to use TextExpander.