Reputation: 659
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 234
to 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.
Upvotes: 2
Views: 2662
Reputation: 2149
https://regex101.com/r/zV5zV2/1
str = '234 + \n 823 + sqrt(4) \n 7880 - cos(16)\t'
re = /(\S)+(?=\s*$)/gm
lastWords = str.match(re)
console.log(lastWords) //logs ["+", "sqrt(4)", "cos(16)"]
Input string is multiline to illustrate different possibilities.
Upvotes: 1
Reputation: 318192
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);
Upvotes: 4
Reputation: 36101
.(?=\s*$)
.
- a character(?=)
- positive lookahead to verify the existence of, but not include in the match\s*
- zero or more spaces$
- til the end of the stringUpvotes: 4