Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript looks for substrings


May 09, 2021 CoffeeScript


Table of contents


Find substrings

Problem

You need to search for a string and return the starting position of the match or the matching value itself.

Solution

There are several ways to do this using regular expressions. Some of these methods are called RegExp patterns or objects, and some are called String objects.

RegExp object

The first way is to call the test method in RegExp mode or objects. The test method returns a Boolean value:

match = /sample/.test("Sample text")
# => false

match = /sample/i.test("Sample text")
# => true

The next way is to call the exec method in RegExp mode or in an object. The exec method returns an array or an empty value that matches the information:

match = /s(amp)le/i.exec "Sample text"
# => [ 'Sample', 'amp', index: 0, input: 'Sample text' ]

match = /s(amp)le/.exec "Sample text"
# => null

String object

The match method matches a given string to an expression object. An array with a "g" identity is returned with a match, only the first match is returned without a "g" identity, or null is returned if no match is found.

"Watch out for the rock!".match(/r?or?/g)
# => [ 'o', 'or', 'ro' ]

"Watch out for the rock!".match(/r?or?/)
# => [ 'o', index: 6, input: 'Watch out for the rock!' ]

"Watch out for the rock!".match(/ror/)
# => null

The search method matches regular expressions with strings, and returns the starting position of the match if found, and -1 if not found.

"Watch out for the rock!".search /for/
# => 10

"Watch out for the rock!".search /rof/
# => -1

Discuss

Regular expressions are a powerful way to test and match substrings.