skip to Main Content

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


  1. function checkBracketTyping(previousText, currentText) {
      const openingBrackets = ['['];
      const closingBrackets = [']'];
      const bracketStack = [];
    
      for (let i = 0; i < currentText.length; i++) {
        const char = currentText[i];
    
        if (openingBrackets.includes(char)) {
          bracketStack.push(char);
        } else if (closingBrackets.includes(char)) {
          if (bracketStack.length === 0) {
            return false;
          }
    
          bracketStack.pop();
        }
      }
    
     return bracketStack.length === 0;
    }
    
    const previousValue = "Leave[Test[Again[Nested[]]]";
    const currentValue = "Leave[Test[Again[Nested[]]]SomeText";
    
    const isValidBracketTyping = checkBracketTyping(previousValue, currentValue);
    console.log(isValidBracketTyping);
    

    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.

    Login or Signup to reply.
  2. 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 and selectionEnd 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:

    const textarea = document.querySelector("textarea");
    textarea.onbeforeinput = (evt) => {
      const { selectionStart, selectionEnd, value } = textarea;
      const bracketStart = value.indexOf("[");
      const bracketEnd   = value.lastIndexOf("]");
      
      if (selectionStart <= bracketStart || selectionEnd > bracketEnd) {
        evt.preventDefault();
      }
      if (evt.inputType === "deleteContentBackward" && selectionEnd === bracketStart + 1) {
        evt.preventDefault();
      }
      if (evt.inputType === "deleteContentForward" && selectionStart === bracketEnd) {
        evt.preventDefault();
      }
    }
    <textarea>Leave[]</textarea>

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search