I am trying to retrieve the index of html elements in a list using Jquery 3.4+.
The common solution can be found in posts like this one or this one.

I have implemented it and it runs well until the values I am trying to retrieve are none others than regular expressions.
Here's a fiddle of what I have tried:

//let myVar = $("#myList").find(`option[text='^.*\.xlsx'])`)[0].index;
let myVar = $("#myList").find(`option:contains('^.*\.xlsx')`)[0].index;
console.log(myVar+"");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select size="1" id="myList"> 
     <option selected style="width:100%;">^.+\.(txt|csv|xlsx)</option>
     <option style="width:100%;">^.+\.(jpg|jpeg|png|svg|bmp)</option>
     <option style="width:100%;">^.*\.xlsx</option>
     <option style="width:100%;">^.*\.docx</option>
     <option style="width:100%;">^.*\.csv</option>
     <option style="width:100%;">^.*\.pdf</option>
</select>

I'd like to add that I can't escape characters nor change the value of what I'm looking for.
Is there a way to get it working for any value regardless of it being a standard text, a regular expression or whatever could be injected in the search function?

推荐答案

仍然使用相同的策略,采用jQuery通过:contains Select 器https://api.jquery.com/contains-selector/#contains1 Select 元素

但您需要转义反斜杠\,将每个字符替换为\\\\

以下是一个模拟从文本输入值获取输入数据的演示:

function fetchInput(){
  return document.getElementById('input').value;    
}

function search(){
  const searchTerm = fetchInput();
  const escaped = searchTerm.replace(/\\/g, '\\\\');

  let index = $(`#myList option:contains('${escaped}')`)?.index();

  console.log(`index: ${index}`);
}
button{
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Search</h1>
<input id="input" value="^.*\.xlsx">
<button onclick="search();">Search</button>

<hr>

<select size="1" id="myList"> 
     <option selected style="width:100%;">^.+\.(txt|csv|xlsx)</option>
     <option style="width:100%;">^.+\.(jpg|jpeg|png|svg|bmp)</option>
     <option style="width:100%;">^.*\.xlsx</option>
     <option style="width:100%;">^.*\.docx</option>
     <option style="width:100%;">^.*\.csv</option>
     <option style="width:100%;">^.*\.pdf</option>
</select>

Javascript相关问答推荐

为什么我达到了时间限制!?LeetCode链接列表循环(已解决,但需要解释!)

在JavaScript中对大型级联数组进行切片的最有效方法?

微软Edge Select 间隙鼠标退出问题

zoom svg以适应圆

格式值未保存在redux持久切片中

当点击注册页面上的注册按钮时,邮箱重复

虚拟滚动实现使向下滚动可滚动到末尾

我的角模板订阅后不刷新'

在WordPress中使用带有WPCode的Java代码片段时出现意外令牌错误

本地库中的chartjs-4.4.2和chartjs-plugin-注解

如何将数组用作复合函数参数?

DOM不自动更新,尽管运行倒计时TS,JS

如何访问此数组中的值?

我正在试着做一个TicTacToe Ai来和我玩.但是,我试着在第一个方块被点击时出现一个X,然后在第二个方块之后出现一个O

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

使用CEPRESS截取时,cy.Wait()在等待5000ms的第一个路由请求时超时

将Singleton实例设置为未定义后的Angular 变量引用持久性行为

在此div中添加一个类,并在一段时间后在Java脚本中将其删除

浮动标签效果移除时,所需的也被移除

CSS网格使页面自动滚动