gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:54:45 25 4
gpt4 key购买 nike

如果任务不需要,我不想使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com