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

How can I find the last instance of substring A before the first instance of substring B?

本文关键字:实例 字符串 最后一个 第一个      更新时间:2023-09-26

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

<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(,我们称之为substring A,它位于substring B之前,如果存在的话。通过查找,我的意思是在字符串中获取换行符的索引。

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

使用

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

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

注意:我展示的简单代码假设会找到substringB。如果要在查找substringA之前显式测试该测试,则可以添加if测试来检查该subBIndex != -1