Find the position of a word in a text

时间:2017-06-20 12:39:35

标签: javascript jquery

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>

4 个答案:

答案 0 :(得分:2)

您如何看待这个?

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>

答案 1 :(得分:2)

您可以使用anchorOffset来确定所选内容的第一个字符的索引(感谢@ tech2017)。

在那之后,这是计算在该指数之前有多少单词的问题。

计算单词的最简单方法是计算空格。我们将在\s+上拆分,以确保我们account for multiple spaces, newlines and more.

注意:我不知道它在所有浏览器中的效果如何。一定要测试!

$(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>

答案 2 :(得分:0)

您可以使用anchorOffset获取所选文本的位置(基于索引0)。 检查这个小提琴:

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

&#13;
&#13;
$(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();
  });

});
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:-2)

您必须计算空白字符,然后在结果中添加1。

示例:此 1 2 我的 3 < /强>段的 4 和<强> 5 6 想的 7 以<强> 8 获取的 9 10 11 本文的段落。