akila arasan
akila arasan

Reputation: 747

How to detect if a particular string is present at the start of a new line inside a textarea using javascript?

I have a text area where I need detect if '+' is followed by a space character at the start of each new line.I can get the keyCode on keyDown event,However this will return the keyCode even if the character is present in the middle of the string.I need to call a function only if the particular character combination is at the start of the new line in the text area.Could any one suggest me how to do this?

Upvotes: 0

Views: 84

Answers (1)

Alessandro
Alessandro

Reputation: 4472

You need to intercept when the user put the string + and (space) in a textarea and check in what position is it.

You could check the previous characters of last digited key, so:

  • Listen on key down event
  • Check if last key is space (because is the last char of the sequence you're looking for)
  • Then check the previous characters, in your case a newLine (\n) followed by the string "+ "

$("#test").keydown(function(e){
  if(e.key==' ')
    console.log(startsWith(e.target, '\n+'));
});

/*
  Returns true when:
  - text in 'target' starts with 'exp'
  - starting by current cursor position
*/
function startsWith(target, exp){
  var expLen = exp.length;
  var str = $(target).val();
  if(target.selectionStart > expLen){
    str = $(target).val();
  } else {
    if("\n" + $(target).val() == exp){
      return true;
    }
  }
  
  var start = target.selectionStart - expLen;
    
  var subStr = $(target).val().substr(start, expLen);
  if(subStr==exp) {
    return true;
  } else {
    return false;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test"></textarea>

Note: I added following condition

if(target.selectionStart > expLen){
  str = $(target).val();
} else {
  if("\n" + $(target).val() == exp){
    return true;
  }
}

To find "+ " expression at the begin of the textarea's text.

I hope it helps you. Bye.

Upvotes: 1

Related Questions