3
votes

I am new to angularjs and webdevelopoment. Here, I do have on string and which is the selected string, its like -

var getSelectedText = function() {
  var text = "";
  if (typeof window.getSelection !== "undefined") {
    text = window.getSelection().toString();
  } else if (typeof document.selection !== "undefined" && document.selection.type === "Text") {
    text = document.selection.createRange().text;
  }
  $scope.annotations = annotationList();
  return text;
};

Now, this is getting selected from the a string which is show on tab. Now, Suppose ,

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

this is a string and I want to get the start and endoffsets of a string which is the selected string

but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised

So, How can I get this in javascript?

1

1 Answers

0
votes

give this a try and check out the comments:

var str = 'a string to search for a value within, we can add as many words as we want here';

function findWithin(str, searchTerm){
  var index = str.indexOf(searchTerm);
  if(index !== -1){
    // at this point we know the string is within the text
    // the start offset will be the place we found the searchTerm
    // the end offset will be the length of the whole str minus the length from the start of the str to the end of the searchTerm

    var endOfSearchTerm = index + searchTerm.length;
    var endOffset = str.length - endOfSearchTerm;
    return { startOffset: index, endOffset:  endOffset}
  } else {
     return 'string not found in text!'
  }
}

findWithin(str, 'we can add as many')