javascript - 从字符串中获取字符串的startoffset和endoffset

标签 javascript jquery css angularjs html

我是 angularjswebdevelopoment 的新手。在这里,我确实有一个字符串,它是选定的字符串,就像 -

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;
};

现在,这是从选项卡上显示的字符串中选择的。现在,假设,

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.

这是一个字符串,我想获取所选字符串的开头和结尾

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

那么,我怎样才能在 javascript 中得到它呢?

最佳答案

尝试一下并查看评论:

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')

关于javascript - 从字符串中获取字符串的startoffset和endoffset,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49513160/

相关文章:

javascript - 设置 Twitter API,获取最后几条推文

jquery - IE8 中通过 jQuery 设置的 margin-top 不更新

javascript - 为什么提交按钮会导致其他选项卡?

javascript - 防止双击导致 HTML 表单中的重复提交

javascript - jQuery 用户界面 : How to check whether another instance of widget is opened?

javascript - AngularJS:根据隐藏子项的数量隐藏父项

javascript - 如何在数组中更深一层

javascript - Knockout动态更新observableArray值

c# - 没有模型和 Ajax 的 POST Json

html - 如何将页眉和页脚更改为全宽