Javascript 从字符串中获取字符串的startoffset和endoffset
我不熟悉Javascript 从字符串中获取字符串的startoffset和endoffset,javascript,jquery,css,angularjs,html,Javascript,Jquery,Css,Angularjs,Html,我不熟悉angularjs和webdevelopment。在这里,我有一个字符串,它是所选的字符串,类似于- var getSelectedText=function(){ var text=“”; if(typeof window.getSelection!=“未定义”){ text=window.getSelection().toString(); }else if(type of document.selection!=“未定义”&&document.selection.type==“文
angularjs
和webdevelopment
。在这里,我有一个字符串,它是所选的字符串,类似于-
var getSelectedText=function(){
var text=“”;
if(typeof window.getSelection!=“未定义”){
text=window.getSelection().toString();
}else if(type of document.selection!=“未定义”&&document.selection.type==“文本”){
text=document.selection.createRange().text;
}
$scope.annotations=annotationList();
返回文本;
};代码>尝试一下并查看评论:
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')