如何替换字符串中的最后一个字符 JS



>我正在尝试构建一个计算器,但卡住了。我不知道如何替换最后一个字符(这是一个数学符号(。例如,如果某人单击"+",然后单击"-",则不应显示为"+-"。

我试过:

  • inputDisplay.textContent = inputDisplay.textContent.replace(/(+|-|*|/)$/, this.value); ;

选择字符串末尾的任何数学运算符并将其替换为 "this.value"(也是一个数学符号(。输出为:"1+-/+*"...

  • let lastSymbol = inputDisplay.textContent.slice(-1); inputDisplay.textContent = inputDisplay.textContent.replace(lastSymbol, this.value);

console.log(lastSymbol(记录数学符号(一次一个(,但是当我使用.replace((方法替换"lastSymbol"变量时,数学符号是连接起来的,而不是替换的:"1+-+*"...

  • let stringWithoutLastCharacter = inputDisplay.textContent.slice(0, -1); inputDisplay.textContent = stringWithoutLastCharacter + this.value;

数学符号也连接在一起:"1+-+"...

我不知道如何解决这个问题,所以我在寻求帮助。谢谢。

您的问题不是替换,而是在以下之前添加当前运算符:

if (!symbols.includes(this.value) ) {
// 'this' refers to the 'element' in 'arr.forEach(element.....)' (see below)
// display elements consequently    
inputDisplay.textContent += this.value;     
}

相反,您还应该检查运算符并在 if 语句中替换:

if (!symbols.includes(this.value)) {
// 'this' refers to the 'element' in 'arr.forEach(element.....)' (see below)
// display elements consequently    
   let lastChar= inputDisplay.textContent.length && inputDisplay.textContent.length >0 ?inputDisplay.textContent[inputDisplay.textContent.length] : '';
   if(mathSymbols.includes(this.value)&& mathSymbols.includes(lastChar)){
      inputDisplay.textContent[inputDisplay.textContent.length]=this.value;
   }
   else{
inputDisplay.textContent += this.value;     
   }
}

只写在电话上,所以请原谅错别字!

编辑:

我使用了您的一次尝试,因为替换不适用于最后一个字符的索引。此外,它是...length-1,可以在新版本中看到:

if (!symbols.includes(this.value) ) {
    // 'this' refers to the 'element' in 'arr.forEach(element.....)' (see below)
       let lastChar = inputDisplay.textContent.length && inputDisplay.textContent.length > 0 ? inputDisplay.textContent[inputDisplay.textContent.length-1] : '';
     console.log('inputDisplay.textContent.length: ' + inputDisplay.textContent.length);
     //console.log('last char: ' + lastChar);
       if (inputDisplay.textContent.length>0 && mathSymbols.includes(this.value) && mathSymbols.includes(lastChar)) {
          //inputDisplay.textContent[inputDisplay.textContent.length-1] = this.value; 
         let stringWithoutLastCharacter = inputDisplay.textContent.slice(0, -1);
inputDisplay.textContent = stringWithoutLastCharacter + this.value;
        // console.log('lastCharacter: '+ inputDisplay.textContent[inputDisplay.textContent.length-1]);
           //console.log('this value: ' + this.value);     
       } else {
           // display elements consequently  
        inputDisplay.textContent += this.value; 
        // console.log('else, this value: ' + this.value);    
        }
    }      

最新更新