const
input
=
"As I was going to Saint Ives"
;
input
.
startsWith
(
"As"
)
// true
input
.
endsWith
(
"Ives"
)
// true
input
.
startsWith
(
"going"
,
9
)
// true -- start at index 9
input
.
endsWith
(
"going"
,
14
)
// true -- treat index 14 as the end of the string
input
.
includes
(
"going"
)
// true
input
.
includes
(
"going"
,
10
)
// false -- starting at index 10
input
.
indexOf
(
"going"
)
// 9
input
.
indexOf
(
"going"
,
10
)
// -1
input
.
indexOf
(
"nope"
)
// -1
Note that all of these methods are case sensitive. So
input.startsWith("as")
would
be false. If you want to do a case-insensitive comparison, you can simply convert the
input to lowercase:
input
.
toLowerCase
().
startsWith
(
"as"
)
// true
Note that this doesn’t modify the original string;
String.prototype.toLowerCase
returns a new string and doesn’t modify the original string (remember that strings in
JavaScript are immutable).
If we want to go a step further and find a substring and
replace
it, we can use
String.prototype.replace
:
const
input
=
"As I was going to Saint Ives"
;
const
output
=
input
.
replace
(
"going"
,
"walking"
);
Again, the original string (
input
) is not modified by this replacement;
output
now
contains the new string with “going” replaced with “walking” (we could have assigned
back to
input
, of course, if we really wanted
input
to change).
Constructing Regular Expressions
Before we get into the complexities of the regex metalanguage, let’s talk about how
they’re actually constructed and used in JavaScript. For these examples, we’ll be
searching for a specific string, just as before—an overkill for regexes, but an easy way
to understand how they’re used.
Regexes in JavaScript are represented by the class
RegExp
. While you can construct a
regex with the
RegExp
constructor, regexes are important enough to merit their own
literal syntax. Regex literals are set off with forward slashes:
const
re1
=
/going/
;
// regex that can search for the word "going"
const
re2
=
new
RegExp
(
"going"
);
// equivalent object constructor
There is a specific reason to use the
RegExp
constructor that we’ll cover later in this
chapter, but except for that special case, you should prefer the more convenient literal
syntax.
238 | Chapter 17: Regular Expressions