Reputation: 774
$('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
Reputation: 464
.select
doesn't work like you are intending it to.
$("#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'.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
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
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