JavaScriptで文字列を検索するメソッドのまとめです。それぞれ記述の仕方と戻り値に特徴があります。
以下のhtmlの構造でテストします。
<p class="txt">HTML・CSS・JavaScript・jQuery・Photoshop・Illustrator・XD・ツール・フリーソフト・その他</p>
<input type="button" class="btn01" value="indexOf(文字列あり)">
<input type="button" class="btn02" value="indexOf(文字列なし)"><br><br>
<input type="button" class="btn03" value="search(文字列あり)">
<input type="button" class="btn04" value="search(文字列あり:正規表現)">
<input type="button" class="btn05" value="search(文字列なし)"><br><br>
<input type="button" class="btn06" value="match(文字列あり)">
<input type="button" class="btn07" value="match(文字列なし)"><br><br>
<input type="button" class="btn08" value="test(文字列あり)">
<input type="button" class="btn09" value="test(文字列なし)">
indexOfメソッドは第1引数に検索したい文字列を指定します。正規表現は使えません。文字列の先頭(0番目)から順番に検索して最初に一致した位置(index番号)を数値で返します。一致しない場合の戻り値は「-1」です。
searchメソッドは使い方はindexOfと同じですが、第1引数に正規表現が使える部分がindexOfとは異なります。文字列の指定も可能です。
matchメソッドは第1引数の検索したい文字列の指定に正規表現を使います。文字列は指定できません。一致した場合は一致した文字列を配列で返すため、検索文字列の取得にはmatchメソッドを利用します。一致しない場合の戻り値は「null」です。
testメソッドは検索したい正規表現のパターンから呼び出し、第1引数にはチェックする文字列全体を指定します。一致した場合の戻り値は「true」、一致しない場合の戻り値は「false」です。
$(function() {
var txt = $('.txt').text();
$('.btn01').on('click', function() {
var result01 = txt.indexOf('JavaScript');
console.log(result01);
});
$('.btn02').on('click', function() {
var result02 = txt.indexOf('WordPress');
console.log(result02);
});
$('.btn03').on('click', function() {
var result03 = txt.search('JavaScript');
console.log(result03);
});
$('.btn04').on('click', function() {
var result04 = txt.search(/JavaScript/);
console.log(result04);
});
$('.btn05').on('click', function() {
var result05 = txt.search('WordPress');
console.log(result05);
});
$('.btn06').on('click', function() {
var result06 = txt.match(/JavaScript/);
console.log(result06[0]);
});
$('.btn07').on('click', function() {
var result07 = txt.match(/WordPress/);
console.log(result07);
});
$('.btn08').on('click', function() {
var result08 = /JavaScript/.test(txt);
console.log(result08);
});
$('.btn09').on('click', function() {
var result09 = /WordPress/.test(txt);
console.log(result09);
});
});
//result01
9
//result02
-1
//result03
9
//result04
9
//result05
-1
//result06
JavaScript
//result07
null
//result08
true
//result09
false





