-1

I need index of HTML string, I have index of Textual string. How can i find HTML string index that is same as Textual string index?

HTML string

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

textual string

My name is Aaliyah and i am from @

caret position is 18.

Now please tell me, how can i find this 18 caret position index in HTML string? Thanks

Note: I need HTML index of html string. I have caret position of Textual string. They both should point to the same text. weather it is HTML string, or same textual string(with no HTML element).

ahsan ayub
  • 286
  • 2
  • 17
  • Use field.selectionStart example .[in this answer](https://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field/48150864#48150864) – Oleksandr Hrin Jan 14 '21 at 10:15
  • @OleksandrGrin it will only work when type is text area or text. For me its div with contentable property set to true. – ahsan ayub Jan 14 '21 at 10:19

1 Answers1

0

You can get all the occurrences of what you are looking for inside the HTML string using a Regular Expression.

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);
Kostas
  • 1,903
  • 1
  • 16
  • 22
  • Brother, It will get the text , which i already have, i need index position of HTML string. Because when you are using innerText it removes all the HTML TAGS and elements. I need it with all HTML parameters. – ahsan ayub Jan 14 '21 at 10:32
  • You need the index of the position of an already existing element? Or you already have the html string? If yes then ````'
    My name is Aaliyah  and i am from @.
    '[18] ```` is the answer.
    – Kostas Jan 14 '21 at 10:38
  • Yes, i already have the HTML string, i got it from div.innerHTML. I am using cater position to insert a character, but cater position is of textual string index not of html index. – ahsan ayub Jan 14 '21 at 10:46
  • I need html string index in number just like cater position of textual string – ahsan ayub Jan 14 '21 at 10:51
  • You have changed your answer, i see! but what if two tags are identical , it will always return first one, but not second one. so , its not solution i am looking for. – ahsan ayub Jan 14 '21 at 11:01
  • it will give me all occurrences and i have no way to find, which occurence represent the caret index that i have. I need HTML index of html string. I have caret position of Textual string. They both should point to the same text. weather it is HTML string, or same textual string(with no HTML element). – ahsan ayub Jan 14 '21 at 12:11