この記事では、文字列に指定されたサブストリングが含まれているかどうかを判断するJavaScriptの方法について説明します。参照のためにそれを共有してください。特定の分析は次のとおりです。
次のJSコードは、文字列オブジェクトの含有方法を定義して、文字列にサブストリングが含まれているかどうかを判断します。これは非常に便利です。
if(!array.prototype.indexof){array.prototype.indexof = function(obj、start){for(var i =(start || 0)、j = this.length; i <j; i ++){if(this [i] === obj){return i; }} return -1; }} if(!string.prototype.contains){string.prototype.contains = function(arg){return !! 〜this.indexof(arg); };}以下は、ブラウザで実行できる詳細な使用例です。
コードを次のようにコピーします。2つの文字列を入力して、1つが文字列2が含まれているかどうかを確認します。<br> <br>
文字列1:<入力id = "foo" type = "text" value = "クイックブラウンフォックスがジャンプします"> <br>
文字列2:<入力id = "bar" type = "text" value = "foxジャンプ"> <br> <br>
<button onclick = "checkstring()"> [文字列1が文字列2 </button>が含まれている場合]をクリックしてクリックします
<スクリプト>
if(!array.prototype.indexof){
array.prototype.indexof = function(obj、start){
for(var i =(start || 0)、j = this.length; i <j; i ++){
if(this [i] === obj){return i; }
}
return -1;
}
}
if(!string.prototype.contains){
string.prototype.contains = function(arg){
return !! 〜this.indexof(arg);
};
}
function checkString(){
var foo = document.getElementById( "foo")。value;
var bar = document.getElementById( "bar")。value;
アラート(foo.contains(bar));
}
</script>
この記事がみんなのJavaScriptプログラミングに役立つことを願っています。