此方法执行搜索以查找正则表达式与此字符对象之间的匹配项。
search() - 语法
string.search(regexp);
regexp - 正则表达式对象。如果传递了非RegExp对象,则使用新的RegExp(obj)将其隐式转换为RegExp。
search() - 返回值
如果成功,搜索将返回字符串内的正则表达式的索引。否则,它返回-1。
search() - 示例
var re=/apples/gi; var str="Apples are round, and apples are juicy."; if ( str.search(re) == -1 ) { console.log("Does not contain Apples" ); } else { console.log("Contains Apples" ); }
运行上面代码输出
Contains Apples.