javascript - 如何在innerHTML 字符串中查找文本索引?提供插入符号位置
问题描述
我需要 HTML 字符串的索引,我有文本字符串的索引。如何找到与文本字符串索引相同的 HTML 字符串索引?
HTML 字符串
<div> My name is <span contenteditable="false" id="3" style=" color:rgb(35, 149, 255);">Aaliyah</span> and i am from @.</div>
文本字符串
我的名字是 Aaliyah,我来自@
插入符号的位置是18。
现在请告诉我,如何在 HTML 字符串中找到这 18 个插入符号位置索引?谢谢
注意:我需要 html 字符串的 HTML 索引。我有文本字符串的插入符号位置。他们都应该指向相同的文本。天气它是 HTML 字符串,或相同的文本字符串(没有 HTML 元素)。
解决方案
您可以使用正则表达式在 HTML 字符串中找到您要查找的所有内容。
let HTMLString = `<div> My name is <span contenteditable="false" id="3" style=" color:rgb(35, 149, 255);">Aaliyah</span> and i am from @.</div>`;
let lookingFor = 'div';
let regex = new RegExp(`${lookingFor}`, 'gi');
let result, indices = [];
while ((result = regex.exec(HTMLString)) ) {
indices.push(result.index);
}
console.log(indices);
推荐阅读
- webpack - 已解决:具有 Web 上下文的 Jhipster 使用错误的 url 解析 i18n 资源
- javascript - 计算一个值在嵌套对象的多级数组中出现的次数
- c# - 初始化对象时强制进行属性初始化
- python - 网络词典解析建议
- python - 在分配之前引用的局部变量(没有意义......)
- mysql - Rails 6.1 where.missing 自连接
- c++ - 指向函数的向量
- next.js - 如何将 blurha.sh 与新的 Next.JS 图像组件一起使用
- html - srcset / sizes - 无法响应 img 工作
- php - 教义——三表关系