javascript 在索引后查找字符串的第一个索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19162845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:37:13  来源:igfitidea点击:

Find first index of a string after index

javascript

提问by Alon Shmiel

I have a string: "www.google.com.sdg.jfh.sd"

我有一个字符串:“www.google.com.sdg.jfh.sd”

I want to find the first ".s" string that is found after "sdg".

我想找到在“sdg”之后找到的第一个“.s”字符串。

so I have the index of "sdg", by:

所以我有“sdg”的索引,通过:

var start_index = str.indexOf("sdg");

now I need to find the first ".s" index that is found after "sdg"

现在我需要找到在“sdg”之后找到的第一个“.s”索引

any help appreciated!

任何帮助表示赞赏!

采纳答案by matewka

This code might be helpful

此代码可能会有所帮助

var string = "www.google.com.sdg.jfh.sd",
  preString = "sdg",
  searchString = ".s",
  preIndex = string.indexOf(preString),
  searchIndex = preIndex + string.substring(preIndex).indexOf(searchString);

You can test it HERE

你可以在这里测试

回答by lukas.pukenis

There's a second parameter which controls the starting position of search:

还有第二个参数控制搜索的起始位置:

String.prototype.indexOf(arg, startPosition);

So you can do

所以你可以做

str.indexOf('s', start_index);

回答by jasonslyvia

var str = "www.google.com.sdg.jfh.sd";
var search = "sdg";
var start_index = str.substring(str.indexOf(search) + search.length).indexOf(".s");