Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last character in javascript string ignoring whitespace

Given string:

234 + (note the space after +)

I want to write a function that determines if there was one of certain characters there (in this case +)

Background

I have an input to hold a mathematics equation

I want to have buttons that can add 2-digit, 3-digit numbers etc. While also allowing the user to type in their own numbers and operators.

So if the input is empty, and the user clicks the 3-digit button, I want 234to be added to the input.

If he clicks again, I want to add + 234 (as there is no operator there)

Now, if the user types another + (optionally followed by any amount of spaces), I want to add only 234 again

tldr

How can i read the last non-whitespace character in a string? jquery preferred, vanilla is also ok.

like image 975
user3787706 Avatar asked Jun 23 '26 19:06

user3787706


1 Answers

First trim off any whitespace, then just get the last character and compare it to something

var str = "234 + ";

str = str.trim();

var last = str.charAt(str.length - 1);
like image 118
adeneo Avatar answered Jun 25 '26 09:06

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!