I am having trouble recognizing the final character within a string

Starting to learn Javascript and working on a basic calculator. My goal is to track the last character entered in the calculator display to prevent double symbols like (++, ./, *-, etc.)

Since the input comes as a string, I've attempted using the methods .slice(-1) or .charAt(str.length-1), but they seem to return the previous character instead of the last one.

For instance, if I type in the number 839, the methods give me the 3 instead of the 9. Any thoughts on why this might be happening?

I suspect it's related to where I'm calling these methods in my code, but I haven't been able to pinpoint the issue yet.

You can access the full code here: https://github.com/coccagerman/calculator Here's the function responsible for displaying values in the calculator:

function printButton(e) {
    let calculatorDisplay = document.getElementById("calculatorDisplay").innerHTML
    let pressedKeyValue = e.target.getAttribute('value')
    var lastCharacter

    console.log('pressedKeyValue ' + pressedKeyValue)
    console.log('calculatorDisplay ' + calculatorDisplay)

    // Your conditional statements go here
        
}

Answer №1

Make sure to always update the calculatorDisplay variable after making any changes to the element it represents within the method.

calculatorDisplay += pressedKeyValue
document.getElementById("calculatorDisplay").innerHTML = calculatorDisplay 
lastCharacter = calculatorDisplay.slice(-1)

Answer №2

To retrieve the last character of a string, you have several methods available such as using the slice or charAt functions.

const string = "+-";

// Method 1
const lastCharacter1 = string.slice(string.length - 1);
console.log(lastCharacter1);

// Method 2
const lastCharacter2 = string.slice(-1);
console.log(lastCharacter2);

// Method 3
const lastCharacter3 = string.split("").pop();
console.log(lastCharacter3);

// Method 4
const lastCharacter4 = string.charAt(string.length - 1);
console.log(lastCharacter4);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to switch between my two images upon clicking?

When I click on an image, it changes to a different image. I achieved this by altering the source of the image upon clicking. Now, my goal is to incorporate a smooth transition between the two images after they are clicked. I attempted to stack the two im ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

Encountering difficulties in transferring bulky files with the request module in Node.js

When working on a Node.js project, I encountered an issue with transferring files from the computer to the server. While I am able to successfully send files that are up to 2mb in size, larger files fail to upload. Here is the code snippet I am using: var ...

The never-ending cycle and memory overload that occur when using Angular's ngRoute

It seems like I may have hit a roadblock while attempting to get ng-view and ngRoute up and running. Everything appeared to be functioning correctly, but it looks like the entire process is caught in a loop. Just to provide some context, I am working with ...

Tips for making a dropdown menu within an Ionic Side menu

Looking for guidance on creating a sub menu in the ionic framework? I'm new to AngularJS and ionic framework, but eager to learn. Below is the code snippet I used to create a dropdown list component: <ion-side-menu side="left"> <ion-co ...

Integrating Gesture Handling in Leaflet JS for two-finger scrolling enforcement

Have you ever noticed that when you're using a mobile device and scrolling down a webpage with a Google map, the map goes dark and prompts you to "Use two fingers to move the map"? https://i.stack.imgur.com/4HD1M.jpg I am interested in incorporating ...

Showing Firestore Data as a map type: Issue encountered - React child cannot be an Object

Retrieving data from firestore: const [product, setProduct] = useState([]); const fetchProducts = async () => { const querySnapshot = await getDocs(collection(db, "products")); const productsArray = []; querySnapshot.forEach((doc) => { ...

Strategies for optimizing PPI and DPI in responsive design

Imagine having two monitors: one 15.5 inches with a resolution of 1920 x 1080 and the other 24 inches with the same resolution. The first monitor has a pixel density of around 72 PPI, while the second has around 90 PPI. If I apply a media query in CSS for ...

Employ material-ui default prop conditionally

I am implementing a StepLabel component in material ui. Depending on the props passed to the parent, I may need to make changes to the icon property of the StepLabel: interface Props { customClasses?: ClassNameMap; customIcon?: ReactNode; } const MySt ...

Upon returning to the previous page, the checkbox remains checked and cannot be unchecked

Here is the code I'm using to append checkbox values with a hash in the URL. However, when navigating back, the checkboxes remain checked. Take a look at the code snippet below: <html> <head> <script src="http://ajax.googleapis.com/aja ...

Tips for sending parameters in onClick within a React Functional Component

In my ReactJS Functional Component, I need to pass a few values when a button is clicked. The code snippet for this functionality is below: <span className="edit" onClick={ onClickEdit(value.title, value.details)}> <img src={editImg} height=" ...

template strings receive null value

I am currently facing an issue with the execution of certain template literals in my jQuery functions. Although some are functioning as expected, there is a specific block that is not being executed. function viewUserDetails(data) { // retrieves integer v ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

Error: Provider not recognized

Currently, I am in the process of creating a basic chat application using express.js, socket.io, and angular. The functionality seems to be working properly. However, I am encountering an issue where the socket message event is not synchronizing and displa ...

How Should One Properly Describe an Object with Multiple Dimensions?

PHP features multidimensional arrays, meaning an array that contains multiple arrays within it. When working with JavaScript, how does one refer to an object that holds multiple objects? Is it called a multidimensional object or is there a different termi ...

Tips for including images while drafting an article

In my current project, users are able to write articles. One feature of the editor is the ability to upload photos and include them in the article. While this functionality works well, there is an issue with how the photos are handled and stored. Each ar ...

Transferring Data from Mod_rewrite to PHP using HTML and JavaScript for the User Interface

My web application has two components: the front end built with HTML, JavaScript/jQuery, and the back end using PHP. In its previous state, it utilized unsightly URLs such as host/app/Page.php?userid=1... definitely not aesthetically pleasing! But with a ...

Step-by-step guide on implementing a border-bottom for an active link

Is there a way to apply a border-bottom to btn_articles and btn_posts when one of them is clicked? I attempted to use the active class but it did not have the desired effect. Any suggestions or solutions would be greatly appreciated. let btn_articles = ...