Toleo
Toleo

Reputation: 774

Transform String into Array and Select matching words inside the textarea

$('textarea').on('keyup', function(){
  var ths = $(this);
  var array = $(this).val().split(' ');
  array.forEach(function(value){
    if (value.match(/(threewords)/g)) {
        ths.val().select(value);
    }
  })
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea>word twowords threewords</textarea>

What I want to do is to select the matching text inside the textarea if it matches the .match(/(threewords)/g) if I wrote word,

The problem is that I keep getting that .match() is null if there is no match or getting select is not a function if the match exists, But nothing is selected and the error occurs, How can I do what i'm trying to do properly?

Upvotes: 1

Views: 132

Answers (3)

Parama Kar
Parama Kar

Reputation: 464

.select doesn't work like you are intending it to.

  1. $("#target").select(value) is incorrect syntax. $("#target").select() is a valid syntax but it does not highlight anything it triggers the select event on an element with id 'target'.
  2. The select event is fired when any text is selected, as in, clicked and dragged over by the mouse. It can be handled by attaching a handler to it:

Example:

    $( "#target" ).select(function() {
        $( "div" ).text( "Something was selected" ).show().fadeOut( 1000 );
    });

ths.val().select(value); part of your code is not a function indeed. Hence the error.

ths.val().select(); on the other hand ends up triggering the select event on the matched value which doesn't serve your purpose.

Upvotes: 1

Kokogino
Kokogino

Reputation: 1056

$('textarea').on('keyup', function(){
  var wordToSearch = 'threewords'
  var reg = new RegExp('\\b' + wordToSearch + '\\b')
  var indexStart = $(this).val().search(reg)
  if(indexStart >= 0){
    this.selectionStart = indexStart;
    this.selectionEnd = indexStart + wordToSearch.length;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea>word twowords threewords</textarea>

This code selects threewords if it is written in the textarea.

Upvotes: 2

Gunnar Thoreson
Gunnar Thoreson

Reputation: 313

the match() function returns the matches in an array of strings, i put up an example to demonstrate it easier

try it like this:

$('button').on('click', function(){
    console.log('click');

  var tarea = $('textarea');
  var r = tarea.val().match(/(word)/g);
  console.log(r);
  console.log('jobs done');
});

try it out on jsfiddle

what else you then want to do depends on what you need, if you just want to know if there is a match you can simply do so by checking if the returned array is empty or not.

in this case i use a button to trigger the check for convenience

edit: version without button jsfiddle

Upvotes: 1

Related Questions