如何在子串B的第一个实例之前找到子串A的最后一个实例?

时间:2016-08-03 19:48:10

标签: javascript string

如果不需要任务,我不想使用正则表达式。我在textarea中有一些文字......

googleDetails

...我选择了一段我有兴趣操作的文本,我们称之为static NSString *kGoogleDetails = @"googleUserDetailsDictionary";

<textarea>
    <!-- language-all: lang-cs -->
    [Exception filters][1] give developers the ability to add a condition (in 
    the form of a boolean expression) to a `catch` block allowing the `catch` to 
    execute only if the condition evaluates to `true`.  

    This is different from using an `if` statement inside the `catch` block and 
    re-throwing the exception since this approach stops propagating debug 
    information linked to the original exception.
</textarea>

我希望在substring B之前找到换行符var substringB = 're-throwing the exception since this approach stops propagating'; ,让我们称之为\n,如果存在的话。通过find,我的意思是在字符串中获取linebreak的索引。

这可以用JS字符串函数完成吗?我们需要使用正则表达式吗?

1 个答案:

答案 0 :(得分:2)

使用.indexOf()查找substringB,然后使用.lastIndexOf()查找substringA从那里向后搜索。 .indexOf().lastIndexOf()都有一个可选的 fromIndex 参数。

&#13;
&#13;
var text = document.querySelector("textarea").value;

var substringB = 're-throwing the exception since this approach stops propagating';
var substringA = '\n';

var subBIndex = text.indexOf(substringB);
var subAIndex = text.lastIndexOf(substringA, subBIndex);

console.log(subAIndex);
&#13;
<textarea>
    <!-- language-all: lang-cs -->
    [Exception filters][1] give developers the ability to add a condition (in 
    the form of a boolean expression) to a `catch` block allowing the `catch` to 
    execute only if the condition evaluates to `true`.  

    This is different from using an `if` statement inside the `catch` block and 
    re-throwing the exception since this approach stops propagating debug 
    information linked to the original exception.
</textarea>
&#13;
&#13;
&#13;

注意:我显示的简单代码假定会找到substringB。如果要在查找if之前明确测试subBIndex != -1,可以添加substringA测试以检查<html> <body> <div id="div1" style="width: 581px; height: 643px;"> <div id="div2" style="position: relative; width: 581px; height: 643px; background-image: url("bg.jpg"); background-size: 100% 100%;"> <div id="div3" style="position: absolute; width: 581px; height: 643px;"> <canvas id="canvas1" width="640" height="960" style="z-index: 0; width: 428.667px; height: 643px; transform: translateX(76.1667px) translateY(0px);"></canvas> </div> <div id="div4" style="position: absolute; width: 581px; height: 643px;"> <canvas id="canvas2" width="640" height="960" style="z-index: 1; width: 428.667px; height: 643px; transform: translateX(76.1667px) translateY(0px);"></canvas> </div> </div> </div> </body> </html>