Python-style startswith and endswith string functions in Javascript

The Python language has useful string methods to search for prefixes and suffixes:


my_string.startswith('pre')

The same thing can be achieved in Javascript using the rather powerful search and replace methods.

These methods can either accept strings or regular expressions.  To search for a plain string, use quote marks, for example:


my_string.search('tom');

This will return the index of the first occurence of ‘tom’ in my_string.

To search for a regular expression, use slashes. Regular expressions use special characters to search for particular patterns in strings - we’ll just be using the ’starts with’ (^)  and ‘ends with’ ($) characters. Therefore, our Python-style startswith and endswith tests looks like this:


my_string.search(/^prefix/) ;

my_string.search(/suffix$/);

Note from Alex Macmillan (honorary proof reader)

While the Python functions return a boolean value depending on the match, the Javascript versions return the index of the matched string. If they are not found, the return value will be -1, not false.