javascript - How do I use a template literal in a regular expression?
问题描述
I am writing a test which clicks on certain filters and I notice some discrepancies between browsers. For example On major browsers(Chrome, Firefox, Safari) there are check boxes shown exactly in this format: Checkers, Cheese, Salsa, Butter. When I run the test on IE11 those strings are lower case and because it is lower case, my test is failing. To combat that I was hoping to use regular expressions. The function I am using to click those checkboxes is reusable.
I am puzzled because I am trying to pass the string in the regular expression but the test fails. I then went on to create a template literal and someone pass the string in the regular expression that way and the test still failed. My question is, is there a smarter way to pass in a string variable into a regular expression?
The filterPage looks like:
export default class OrderHistory {
constructor() {
this.filter = Selector(
".filterCheckbox"
}
async selectFilter(text) {
await t.click(this.filter.withText(`/${text}`/i));
}
The test page looks like:
test(“click the cheese filter”, async t => {
const cheeseFilter = Cheese;
await filterPage.selectFilter(cheeseFilter);
});
解决方案
如果您需要动态构建正则表达式,RegExp构造函数可能会完成这项工作,因为它也可以接受 string。
new RegExp(text, 'i');
推荐阅读
- vuejs2 - 在 VUEJS 中日历内的日期上显示名称
- reactjs - 将网站文件放在 public_html 中是否安全
- sql-server - 使用 Terraform 扩展磁盘 SQL Server 虚拟机
- python - 使用 Python 在 Databricks 中的另一个笔记本中动态创建一个笔记本
- python - Groupby 和范围计数并在 Python 中传播
- javascript - 将 React 类组件转换为功能组件,完美渲染但功能丢失?
- c++ - 为什么我的链表是打印地址而不是打印值?
- asp.net-core - Asp.Net Core 5 auth 中间件发生在配置中指定的顺序错误
- java - Spring Boot 更改静态路径模式不自动提供 index.html
- javascript - 如何动态设置选择选项?