美文网首页
查找所有子字符串的所有位置

查找所有子字符串的所有位置

作者: 哒哒DaDa | 来源:发表于2017-08-20 11:02 被阅读32次
var str = "adadfdfseffqdjhuserfsefseetsdg";//字符串
var search = "fse";//要找的子串

function searchSubStr(str, search){
  var pos = [];
  var index = str.indexOf(search);//开始找,找到了,while循环继续找
  while(index > -1){
    pos.push(index);
    index = str.indexOf(search, index+1);//在找到的下一个位置上又开始找,直到找不到了,退出;
  }
  return pos;
}

console.log(searchSubStr(str, search));//[6, 19, 22]

相关文章

网友评论

      本文标题:查找所有子字符串的所有位置

      本文链接:https://www.haomeiwen.com/subject/krcfdxtx.html