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

标签 javascript string

如果任务不需要,我不想使用 Regex。我在文本区域中有一些文本...

<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 字符串函数来完成吗?我们需要为此使用 Regex 吗?

最佳答案

使用.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 将被找到。您可以添加一个 if 测试来检查 subBIndex != -1 如果您想在查找 substringA 之前明确测试它。

关于javascript - 如何在子字符串 B 的第一个实例之前找到子字符串 A 的最后一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38752422/

相关文章:

javascript - 如何使用 jQuery 将 () 替换为 RegEx

javascript - JS/CSS - 函数 openNav() 不适用于主页(仅)

C# - 添加字符串并替换为新字符串

Javascript 模块设计

javascript - 触发点击事件时选择父项?

javascript - jQuery 自动完成功能在 Rails 4 中不起作用

java - 如何在字符串中查找第 n 个出现的字符?

c - 如何读取和输出带有空格和换行符的输入

c - fgets 无法正常工作

regex - PowerShell Regex替换产生空输出