orestiskim
orestiskim

Reputation: 71

Find the position of a word in a text

I am building a JS script and I want to get the position of a word in a text by clicking on it. For example:

This is my paragraph and I want to get the word paragraph of this text.

Let's assume that I am clicking on the paragraph that appears for second time in this text. The result should be 12 as it's the 12th word. How could I do that?

So far I can double click on a word and get it but I also need its position.

 <script> $(document).ready(function() {

        var p = $('p');
        p.css({ cursor: 'pointer' });

        p.dblclick(function(e) {
            var range = window.getSelection() || document.getSelection() || document.selection.createRange();
            var word = $.trim(range.toString());
            if(word != '') {
                alert(word);
            }
            range.collapse();
            e.stopPropagation();
        });

    });</script>

    <p>This is my paragraph and I want to get the word paragraph of this text.</p>

Upvotes: 2

Views: 593

Answers (4)

Kokos
Kokos

Reputation: 9121

You can use anchorOffset to determine the index of the first character of your selection (thanks @tech2017).

After that, it's a matter of counting how many words come before this index.

The easiest way to count words, is counting the whitespace instead. We'll split on \s+ to make sure we account for multiple spaces, newlines and more.

Note: I do not know how well this works in all browsers. Make sure to test!

$(document).ready(function() {

  var p = $('p');
  p.css({
    cursor: 'pointer'
  });

  p.dblclick(function(e) {
    var range = window.getSelection() || document.getSelection() || document.selection.createRange();
    var word = $.trim(range.toString());
    if (word != '') {
      // Count words
      var charIdx = range.anchorOffset;
      var countStr = range.anchorNode.textContent.substr(0, charIdx);
      var wordNumber = (countStr === "") ? 1 : countStr.trim().split(/\s+/).length + 1;
      alert(wordNumber);
    }
    //range.collapse();
    e.stopPropagation();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is my paragraph and I want to get the word paragraph of this text.</p>

Upvotes: 2

Jan Ciołek
Jan Ciołek

Reputation: 1816

What do you think about this?

var p = $('#text');
var text = p.html();

// wrap each word into custom tag with data-i attribute as index
p.html(text.split(' ').map(function(word,index){

  return `<w-d data-i='${index+1}'>${word}</w-d>`

}).join(' '))

// bind actions
$('w-d').click(function(){

  var index = $(this).attr('data-i');
  alert(index)
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="text">Click on my words.</p>

Upvotes: 2

tech2017
tech2017

Reputation: 1806

You can use anchorOffset to get the position of the selected text (index 0 based). Check this fiddle:

https://jsfiddle.net/o2gxgz9r/8945/

$(document).ready(function() {

  var p = $('p');
  p.css({
    cursor: 'pointer'
  });

  p.dblclick(function(e) {
    var range = window.getSelection() || document.getSelection() || document.selection.createRange();
    var word = $.trim(range.toString());
    if (word != '') {
      alert(word);
      var temp = range.anchorOffset;
      alert(temp);
    }
    //range.collapse();
    e.stopPropagation();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is my paragraph and I want to get the word paragraph of this text.</p>

Upvotes: 0

Hakim
Hakim

Reputation: 1

You have to count the Whitespace character and then add 1 to the result.

Example: This1is2my3paragraph4and5I6want7to8get9the10word11paragraph of this text.

Upvotes: -2

Related Questions