2

"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?

6
  • 1
    "inquisitive".endsWith(ive) Er, that sounds like ive is a variable? Commented Jul 6, 2018 at 7:02
  • I didn't understand the part about regex? This is exactly what regex is for. Commented Jul 6, 2018 at 7:03
  • 1
    I think regex it the way to go. But has an 'i' some other stuff and ends with 'e' can be tested with (str.includes('i') && str.endsWith('e')). Maybe an example of what you mean by "is going to be generic" will help. Commented Jul 6, 2018 at 7:05
  • @CertainPerformance you are correct. Sorry! I meant "inquisitive".endsWith('ive') Commented Jul 9, 2018 at 9:48
  • 1
    @Esko Yes, regex is fine, but endsWith does a string match instead of regex match, I meant. Commented Jul 9, 2018 at 9:50

1 Answer 1

4

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'));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.