I have a textarea which by default will have any type of string and a user cannot type unless he is typing inside an opening and closing bracket, such as "Leave[]" I can type inside the bracket but not outside it can be nested too till n levels such as Leave[ Nested[ Test[] ] ], i want a function to check if the user is typing inside the brackets to return true
otherwise false
const checkIfTypingBetweenBrackets=(prev:string,current:string):boolean =>{
// Code goes here
}
2
Answers
We can do this by defining two arrays, openingBrackets and closingBrackets, to represent the types of brackets we are interested in. In this case, it’s just the square brackets [ and ]. We also initialize an empty array called bracketStack to act as a stack data structure. The bracketStack will help us keep track of the opening brackets encountered. We can use a for loop to iterate through each character in the current string. If the current character is an opening bracket ([), we push it onto the bracketStack. This helps us keep track of the opening brackets encountered so far. If the current character is a closing bracket (]), we check if the bracketStack is empty. If it is, there is a closing bracket without a corresponding opening bracket, and we return false. If the bracketStack is not empty, we pop an opening bracket from the bracketStack. This represents that the closing bracket has found its corresponding opening bracket. After iterating through all characters in the current string, we check if there are any remaining opening brackets in the bracketStack. If there are, it means there are unclosed brackets, and we return false. If the function hasn’t returned false at any point, it means all opening brackets have a corresponding closing bracket, and we return true. The function essentially uses a bracketStack to keep track of the opening brackets. If the brackets are properly nested and closed, the bracketStack will be empty at the end, and the function returns true. Otherwise, it returns false.
If I understand correctly the requirements, the fact that there can be nested brackets doesn’t really matter. All that matters is what’s inside the outermost brackets.
So what we can do is check the current
selectionStart
andselectionEnd
positions before the<textarea>
receives the input and compare it against the first index of a[
and the last one of a]
.You’ll also want to take special care of some inputs like backspace or forward delete so that they don’t break the outermost brackets:
Note: I didn’t perform extensive tests on this, and text editing is a real complex matter, so there may be some edge cases that this snippet doesn’t handle.