Masha
Masha

Reputation: 857

Javascript find a position of a word in a string containing HTML

I got the following HTML:

<div id="editable_phrase">
   My 
   <span style="background-color: #19FC49;"> first</span> 
   <span style="background-color: #09AC20;"> first</span> //note 2 firsts here
   <span style="background-color: #D2C3EA;"> phrase</span>
</div>

And the original phrase that is - My first phrase

I need to find a position of a first letter of a selected word in my original phrase. So if I select (highlight with a mouse) phrase, I need to get 10 (or whatever it is). I tried to use charAt() or window.getSelection but still getting wrong results.

Moreover, if I select the same word but in different positions (like inm my example above where there are 2 first words) I get the same result as it finds the position of the first word while I need the second one.

I can use jQuery. Any ideas would be welcome. Thank you.

Upvotes: 3

Views: 3293

Answers (3)

Anthony
Anthony

Reputation: 1581

Here's an answer that combines baao's answer and Joseph Marikle's answer (has since been deleted).

selection.anchorNode.textContent gets the word that is being highlighted.

$("#editable_phrase").bind('mouseup', function(e) {
  var selection;
  var selectedWordPos;
  if (window.getSelection) {
    selection = window.getSelection();
  } else if (document.selection) {
    selection = document.selection.createRange();
  }
  selectedWordPos = $("#editable_phrase").text().replace(/\s\s+/g, ' ').indexOf(selection.anchorNode.textContent.replace(/\s\s+/g, ' '));
  console.log(selectedWordPos);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editable_phrase">
  My
  <span style="background-color: #19FC49;"> first</span>
  <span style="background-color: #D2C3EA;"> phrase</span>
</div>

Upvotes: 1

baao
baao

Reputation: 73271

As you've said you've already got a function to get selection of words, it's as simple as indexOf() - just replace the selectedText below with the word your function returns, and do the action after the text was selected:

let el = document.getElementById('editable_phrase');

let selectedText = "phrase";
let originalPhrase = el.innerText;

console.log(originalPhrase.indexOf(selectedText));
<div id="editable_phrase">
  My
  <span style="background-color: #19FC49;"> first</span>
  <span style="background-color: #D2C3EA;"> phrase</span>
</div>

Upvotes: 2

LiorP
LiorP

Reputation: 94

iterate over the children of the div, and concat them to one string until you get to the desired value, and then return the length of it. for example, something like this: var str = "";

var bool = false;
$('#editable_phrase').children().each(function(){
    if ($(this).text() == "phrase")
        bool = true;
    if (!bool)
        str+=$(this).text();
});

Upvotes: 0

Related Questions