startsWith, endsWith, includes to accept an array

Currently, if you have multiple strings that you want to check on a string, the way to do so is

str.startsWith('a')
str.startsWith('b')

etc.

A neat way to do it would instead be

str.startsWith(['a', 'b'])

This would benefit the string functions startsWith, endsWith, and includes.

2 Likes

That already works by stringifying the array, so it's possible it wouldn't be web-compatible.

2 Likes

Can you give me an example? I'm not sure I follow how stringifying an array allows it to work with startsWith and endsWith.

The concern is that people may be using these APIs with arrays today. Since they coerce their inputs to strings, any arrays will be seen as a single check for the to-stringed version of that array.

"a,b,c".startsWith(["a","b"]) // true (checking if starts with "a,b")

Because of this, these APIs cannot be changed to start accepting arrays with a different behavior because they may break existing code depending on the current to-string behavior.

Ok so I believe there was a miscommunication in the post. Here is a more solid example.
Lets say I want to check if a name has a common ending. I'm using endsWith, and so to check it would look something like the following

name.endsWith('son'); // Bolson, Hendrickson
name.endsWith('ly'); //Presly
name.endsWith('lyn'); // Evelyn, Brooklyn, Madelyn

By accepting an array as an argument, it could be combined. Now the counter argument of breaking existing code is a good point, however, I'm sure that if we're modifying these functions we can account for that possibility with simply checking if the argument passed is an array or a string, or even allowing for a new option if need be.

Are there other languages that have over loaded their string predicates in this way, being able to use arrays as alternative inputs? Is a benefit that it would be familiar to people coming to JS from those languages?

In the mean time, some existing alternatives:

["son", "ly", "lyn"].some(s => name.endsWith(s));
/(son|lyn?)$/.test(name);
1 Like

I don't know the answers to your question, however, I don't think that js should be a the mercy of other languages who have their own quirks. Like how python uses spaces in place of curly brackets or a length function as opposed to a property. Thank you for the work around.

This is another good idea. Many times this would've cleaned up code from having to pass a lambda.