jQuery 检测字符串是否包含某些内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15245979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery detect if string contains something
提问by ngplayground
I'm trying to write jQuery code to detect if a live string contains a specific set of characters then the string alerts me.
我正在尝试编写 jQuery 代码来检测活动字符串是否包含一组特定的字符,然后该字符串会提醒我。
HTML
HTML
<textarea class="type"></textarea>
My Jquery
我的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.
我的代码应该控制台日志提醒我字符串中存在 > <。
回答by yckart
You could use String.prototype.indexOf
to accomplish that. Try something like this:
你可以用它String.prototype.indexOf
来实现。尝试这样的事情:
$('.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.
现代浏览器也有String.prototype.includes
方法。
回答by Denys Séguret
You get the value of the textarea, use it :
你得到 textarea 的值,使用它:
$('.type').keyup(function() {
var v = $('.type').val(); // you'd better use this.value here
if (v.indexOf('> <')!=-1) {
console.log('contains > <');
}
});
回答by topcat3
You can use javascript's indexOf function.
您可以使用 javascript 的 indexOf 函数。
var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";
if(str1.indexOf(str2) != -1){
alert(str2 + " found");
}