CoffeeScript String - search()



Description

This method accepts a regular expression in the form of object and searches the calling string for the given regular expression. If a match occurs, it returns the index of the regular expression inside the string and if it doesn't, it returns the value -1.

Syntax

Given below is the syntax of search() method of JavaScript. We can use the same method in the CoffeeScript code.

string.search(regexp)

Example

The following example demonstrates the usage of search() method of JavaScript in CoffeeScript code. Save this code in a file with name 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"
    

Open the command prompt and compile the .coffee file as shown below.

c:\> coffee -c coffee string_search.coffee

On compiling, it gives you the following 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);

Now, open the command prompt again and run the CoffeeScript file as shown below.

c:\> coffee string_search.coffee 

On executing, the CoffeeScript file produces the following output.

Contains Apples
coffeescript_strings.htm
Advertisements