首页 > 解决方案 > 如何在innerHTML 字符串中查找文本索引?提供插入符号位置

问题描述

我需要 HTML 字符串的索引,我有文本字符串的索引。如何找到与文本字符串索引相同的 HTML 字符串索引?

HTML 字符串

<div> My name is <span contenteditable="false" id="3" style=" color:rgb(35, 149, 255);">Aaliyah</span>&nbsp; and i am from @.</div>

文本字符串

我的名字是 Aaliyah,我来自@

插入符号的位置是18

现在请告诉我,如何在 HTML 字符串中找到这 18 个插入符号位置索引?谢谢

注意:我需要 html 字符串的 HTML 索引。我有文本字符串的插入符号位置。他们都应该指向相同的文本。天气它是 HTML 字符串,或相同的文本字符串(没有 HTML 元素)。

标签: javascripthtml

解决方案


您可以使用正则表达式在 HTML 字符串中找到您要查找的所有内容。

let HTMLString = `<div> My name is <span contenteditable="false" id="3" style=" color:rgb(35, 149, 255);">Aaliyah</span>&nbsp; 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);


推荐阅读