64 lines
1.9 KiB
Plaintext
64 lines
1.9 KiB
Plaintext
== Why is this an issue?
|
|
|
|
When writing code, it is quite common to test patterns against string ends. For a long time, JavaScript did not provide proper support for this use case. As a result, developers have been relying on various programming subtleties to check the start or end of a string. Examples are getting the index of a substring, slicing the beginning of a string, extracting a substring from the head, matching a regular expression beginning or ending with a pattern, and so on.
|
|
|
|
While these approaches are all technically valid, they look more like hacking than anything else, blur the developer's intent, but more importantly affect code readability.
|
|
|
|
Since ES2015, JavaScript provides `String#startsWith` and `String#endsWith`, which are the preferred ways to test patterns against string ends.
|
|
|
|
== How to fix it
|
|
|
|
One should use `String#startsWith` to check the start of a string and `String#endsWith` to check the end.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,javascript]
|
|
----
|
|
const str = 'abc';
|
|
|
|
str[0] === 'a';
|
|
str.charAt(0) === 'a';
|
|
str.indexOf('abc') === 0;
|
|
str.slice(0, 3) === 'abc';
|
|
str.substring(0, 3) === 'abc';
|
|
str.match(/^abc/) != null;
|
|
/^abc/.test(str);
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
str.startsWith('abc');
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,javascript]
|
|
----
|
|
const str = 'abc';
|
|
|
|
str[str.length - 1] === 'c';
|
|
str.charAt(str.length - 1) === 'c';
|
|
str.lastIndexOf('abc') === str.length - 3;
|
|
str.slice(-3) === 'abc';
|
|
str.substring(str.length - 3) === 'abc';
|
|
str.match(/abc$/) != null;
|
|
/abc$/.test(str);
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
str.endsWith('abc');
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith[String#startsWith]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith[String#endsWith]
|