CoffeeScript 字符串 - search()
描述
此方法接受对象形式的正则表达式,并在调用字符串中搜索给定的正则表达式。 如果发生匹配,它返回正则表达式在字符串中的索引,如果不匹配,它返回值 -1。
语法
下面给出的是 JavaScript 的 search() 方法的语法。 我们可以在 CoffeeScript 代码中使用相同的方法。
string.search(regexp)
示例
以下示例演示了在 CoffeeScript 代码中使用 JavaScript 的 search() 方法。 将此代码保存在名为 string_search.coffee 的文件中
regex = /apples/gi
string = "Apples are round, and apples are juicy."
if string.search(regex) == -1
console.log "Does not contain Apples"
else
console.log "Contains Apples"
打开命令提示符并编译.coffee 文件,如下所示。
c:\> coffee -c coffee string_search.coffee
在编译时,它会提供以下 JavaScript。
// Generated by CoffeeScript 1.10.0
(function() {
var regex, string;
regex = /apples/gi;
string = "Apples are round, and apples are juicy.";
if (string.search(regex) === -1) {
console.log("Does not contain Apples");
} else {
console.log("Contains Apples");
}
}).call(this);
现在,再次打开命令提示符 并运行 CoffeeScript 文件,如下所示。
c:\> coffee string_search.coffee
执行时,CoffeeScript 文件产生以下输出。
Contains Apples

