[Javascript Calculator] Check to see if the currentText ended with operators

Hi everyone, I’m working on the Javascript Calculator project and facing with this problem. I want to check if my text ended with any of the operators [±x/], so I write a function to do this by using RegExp and test method, but the problem is it always return true value. Could you explain why is that? Thank you very much, this is my code so far:

function isEndedWithOperator(text) {
    let operatorList = /[+-x/]$/;

    return operatorList.test(text);

When inside [ ], you must escape the - with .

1 Like

Wow thank you so much! I have solved the problem, but could you explain why I have to escape “-”? I thought it is just a normal character, does it have any other functions in RegExp?

In regular expression, [ ] defines a character set. If you put a - between characters it will treat those characters as a range of characters based on the characters’ ASCII codes.

Normally, you would you would use the - for a range of letters in a character set like below:


This would match a single letter between a through z.

1 Like

Oh now I see… thank you very much for your suppor! :slight_smile: