I'm trying to write jQuery code to detect if a live string contains a specific set of characters then the string alerts me.
HTML
<textarea class="type"></textarea>
My Jquery
$('.type').keyup(function() {
var v = $('.type').val();
if ($('.type').is(":contains('> <')")){
console.log('contains > <');
}
console.log($('.type').val());
});
if for example I typed the following
> <a href="http://google.com">Google</a> <a href="http://yahoo.com">Yahoo</a>
My code should console log alert me that there> < present in the string.
asked Mar 6, 2013 at 11:21
ngplayground
21.8k37 gold badges98 silver badges176 bronze badges
-
stackoverflow.com/questions/4444477/…topcat3– topcat32013年03月06日 11:23:00 +00:00Commented Mar 6, 2013 at 11:23
-
What specifically are you trying to do? The answers below does exactly what you ask for, but there might be a better way to go depending on what you're trying to achieve.qwerty– qwerty2013年03月06日 11:26:28 +00:00Commented Mar 6, 2013 at 11:26
-
Use indexOf it will be faster alsoPeeyush– Peeyush2013年03月06日 11:29:42 +00:00Commented Mar 6, 2013 at 11:29
4 Answers 4
You could use String.prototype.indexOf to accomplish that. Try something like this:
$('.type').keyup(function() {
var v = $(this).val();
if (v.indexOf('> <') !== -1) {
console.log('contains > <');
}
console.log(v);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="type"></textarea>
Update
Modern browsers also have a String.prototype.includes method.
answered Mar 6, 2013 at 11:25
yckart
33.6k11 gold badges126 silver badges133 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can use javascript's indexOf function.
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}
answered Mar 6, 2013 at 11:26
topcat3
2,6706 gold badges36 silver badges58 bronze badges
Comments
You get the value of the textarea, use it :
$('.type').keyup(function() {
var v = $('.type').val(); // you'd better use this.value here
if (v.indexOf('> <')!=-1) {
console.log('contains > <');
}
});
answered Mar 6, 2013 at 11:22
Denys Séguret
384k90 gold badges813 silver badges780 bronze badges
Comments
use Contains of jquery Contains like this
if ($('.type:contains("> <")').length > 0)
{
//do stuffs to change
}
answered Mar 6, 2013 at 11:24
Ravi Gadag
15.9k5 gold badges60 silver badges85 bronze badges
Comments
lang-js