-1

I need to get the number of matches in a textarea, but this number is before user is typing.

For example:

@josh @marie @josh @anne <user is typing here> @josh @marie

suppose I want to get @josh, I need to have 2 in my variable, because I have two josh before the cursor/before user is typing.

Any ideas how to get it?

My try:

var p = 'josh';
var regEx = new RegExp(p,"g");


$("#comment").on("keyup",function() {

var number = $('#comment').val().match(regEx).length;

$("#write").html(number);

});

but I can only get the total matches, not only the matches before cursor/before user is typing.

html:

<textarea id=comment>@josh @marie @anne @josh @anne @marie @chloe @josh @anne @josh @marie @anne @josh @anne @marie @chloe @josh @anne</textarea>
<br>
<span id=write></span> matches

https://jsfiddle.net/kstbd2a1/

RGS
  • 4,062
  • 4
  • 31
  • 67

1 Answers1

1

Have a look at the selectionStart property, it can be used to find where the cursor is inside the textarea.

With that knowledge, you can use slice to leave yourself with the starting portion of text, which can then be fed to the RegEx to find matches.

var p = 'josh';
var regEx = new RegExp(p,"g");


$("#comment").on("keyup",function() {

    var val = $(this).val().slice(0,$(this)[0].selectionStart);
    var number = val.match(regEx).length;

$("#write").html(number);

});
Community
  • 1
  • 1
temporalslide
  • 957
  • 6
  • 9
  • 1
    You'll need to do some error checking on it (since moving to the start of the input leaves val as null, which does not like being sliced), but it works as a starting point. – temporalslide Mar 06 '16 at 11:40