javascript - 以正则表达式结尾 - Javascript

标签 javascript

"inquisitive".endsWith('ive') 返回 true

我希望能够搜索类似 "inquisitive".endsWith(i[a-z]e) 的内容,就像以 'i' 结尾以及后面的一些字符一样然后是“e”。我不想进行子字符串匹配,因为此方法将是通用的,并且在大多数情况下不会有正则表达式,但有简单的结束逻辑。

有没有办法,使用 vanilla JS 来实现这一点?

最佳答案

如果您必须仅使用endsWith并且由于任何奇怪的原因而无法使用正则表达式,您可以列出'之间的所有字符串iae''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'));

但这比应有的情况要复杂得多。如果可能的话,更改您的代码以接受使用正则表达式,这样会简单得多,而且应该更可取:

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

关于javascript - 以正则表达式结尾 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51204701/

相关文章:

javascript - 使用 Javascript 添加内容时使 HTML div 展开

Javascript 仅当长度 > 2 时才将字符串中每个单词的首字母大写

javascript - 重构 jQuery 函数

javascript替换选择所有浏览器

javascript - MySQL 的时间验证范围

javascript - 如何在 three.js 中从 BufferGeometry 绘制 2D/3D 网格

javascript - jsx illustrator 脚本 - 加载脚本时将单选选项设置为默认值

javascript 原型(prototype)链 : Rectangle. 原型(prototype) = new Shape() 或 Rectangle.prototype = Shape?

javascript - 根据屏幕宽度裁剪单词

javascript - 如何在 selenium webdriver 中获取文本框的值,Js