jalen201
jalen201

Reputation: 303

Detect repeating characters back to back Javascript

I'm building a JavaScript calculator, and everything is finished, except there is one problem. when a user types in:

3**3 or 7++2 

This brings up a parsing error - How do I detect if there are duplicates back to back?

If we look at the string 3+3+3*2, that's gonna be safe to use, thought if we use the string 3++3+2, that'd be flagged since the back-to-back +'s aren't allowed.

So, if there's ever two characters of the same Type or Ascii value, then flag that string as unsafe to use.

Upvotes: 2

Views: 95

Answers (2)

Abk
Abk

Reputation: 2233

You can get the last item in the console and if it's an operator then return false. Consider this:

var operator = "/*+-^";
var arithmetic = "", lastItem;


 $("span").click(function(){
    // check if number is clicked    
      if($(this).hasClass("num")){
        $("#console").append($(this).text());
        arithmetic += $(this).text();
      }

      //get the last item on the console or in arithmetic string
    lastItem = arithmetic.substr(arithmetic.length-1, arithmetic.length);
    //check if last item is an operator, prevent click of an operator again
      if($(this).hasClass('operator')){
          if(operator.indexOf(lastItem) > -1){
            return false;
          }
          else{
              $("#console").append($(this).text());
              arithmetic += $(this).text();
          }

      }// end if --> checking operator ended.
    if($(this).hasClass('equal')){
         $("#result").append(eval(arithmetic));
          }
      
    });
span{
  padding: 5px;
  background: #ccc;
  margin: 5px;
  cursor: pointer;
  text-align: center;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="num">1</span>
<span class="num">2</span>
<span class="num">3</span>
<span class="operator">+</span>
<span class="operator">*</span>
<span class="equal">=</span><br/><br/>

<div id="console"> </div> <br/>
<div id="result"> </div>

Upvotes: 2

karthik
karthik

Reputation: 159

var regexp = /(\+\+|\-\-|\*\*)/;
regexp.test("22++33");

As per same suggestion you can easily get the match via regex.

Upvotes: 2

Related Questions