Reputation: 3974
"inquisitive".endsWith('ive')
returns true
.
I want to be able to search for something like "inquisitive".endsWith(i[a-z]e)
, which is like ends with 'i' and some character after that and then an 'e'
. I don't want to do a substring match, since this method is going to be generic, and for most of the cases will not have regex but simple endsWith logic.
Is there a way, this can be achieved, using vanilla JS?
Upvotes: 2
Views: 1439
Reputation: 370609
If you have to use only endsWith
and cannot use a regular expression for whatever odd reason, you can come up with a list of all strings between 'iae'
and 'ize'
:
const allowedStrs = Array.from(
{ length: 26 },
(_, i) => 'i' + String.fromCharCode(i + 97) + 'e'
);
const test = str => allowedStrs.some(end => str.endsWith(end));
console.log(test('iae'));
console.log(test('ize'));
console.log(test('ife'));
console.log(test('ihe'));
console.log(test('iaf'));
console.log(test('aae'));
But that's way more complicated than it should be. If at all possible, change your code to accept the use of a regular expression instead, it's so much simpler, and should be much preferable:
const test = str => /i[a-z]e$/.test(str);
console.log(test('iae'));
console.log(test('ize'));
console.log(test('ife'));
console.log(test('ihe'));
console.log(test('iaf'));
console.log(test('aae'));
Upvotes: 4