stringStartsEndsWith
Reports regex patterns that can be replaced with
endsWithorstartsWith.
✅ This rule is included in the ts stylistic presets.
Regular expressions with simple ^ or $ anchors can be replaced with the more readable and performant startsWith() and endsWith() string methods.
This rule detects regex .test() calls that check for simple string prefixes or suffixes and suggests using the dedicated string methods instead.
Examples
Section titled “Examples”Prefix Check with ^
Section titled “Prefix Check with ^”const const hasPrefix: boolean
hasPrefix = /^foo/.RegExp.test(string: string): boolean
Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
test(const str: any
str);const const hasPrefix: any
hasPrefix = const str: any
str.any
startsWith("foo");Suffix Check with $
Section titled “Suffix Check with $”const const hasSuffix: boolean
hasSuffix = /bar$/.RegExp.test(string: string): boolean
Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
test(const str: any
str);const const hasSuffix: any
hasSuffix = const str: any
str.any
endsWith("bar");Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you need case-insensitive matching or other regex features, the string methods won’t work as direct replacements.
This rule ignores patterns with the i (case-insensitive) or m (multiline) flags.