2017-01-07 42 views
2

我正在构建一个JavaScript计算器,并且一切都完成了,除了有一个问题。当用户键入:检测重复字符背靠背Javascript

3**3 or 7++2 

这带来了一个解析错误 - 我如何检测是否有重复背靠背?

如果我们看一下串3+3+3*2,那会是安全的使用,认为如果我们使用字符串3++3+2,该会自背到后面+的是不允许被标记。

因此,如果有两个相同的字符Type或Ascii值,那么将该字符串标记为不安全以便使用。

+1

这是什么都与HTML呢?如果我们没有关于如何解析字符串的信息,我们应该如何知道如何检测背对背重复字符?你想要一个正则表达式来检测任何重复的字符?然后谷歌为“JavaScript正则表达式反向引用”,和/或尝试'/(。)\ 1 /'。 –

+0

你不应该这样做,即使正则表达式工作它只是不正确的方式做这件事。如果你想要你计算器有一些复杂的表达式?你需要的是一种解析算法,首先将你的字符串分解为标记,然后使用'recusive decent parsing'techinque。如果你坚持使用简单的方法,你可以寻找'shunting yard'算法。它可能需要你一段时间,但你会在正确的轨道 – anekix

+0

基本上用户按下计算器上的数字,表达式返回一个字符串,我使用math.js来评估字符串。对于任何计算,但这只是为了好玩,请看看这个谢谢 – jalen201

回答

2

你可以得到控制台中的最后一项,如果它是一个操作员,然后return false。试想一下:

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>

+1

这是我一直在寻找 – jalen201

2

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

按照同样的建议,你可以很容易地通过正则表达式匹配。