如何在子字符串 B 的第一个实例之前找到子字符串 A 的最后一个实例
How can I find the last instance of substring A before the first instance of substring B?
如果任务不需要,我不想使用正则表达式。我在文本区域中有一些文本...
<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
。
相关文章:
- 删除数组Javascript中字符串的所有实例
- 如何通过JS在不干扰其标记的情况下更改HTML文档中字符串的所有实例
- 是否有将基于字符串的JSON转换为Mongoose Schema对象实例的本地功能
- JavaScript:计算字符串中特定整数的实例
- 从 Node.js 模块中的缓冲区实例中逐行读取字符串
- 正则表达式来更改字符串中的所有实例
- javascript正则表达式,将多个实例替换为多行字符串中的单个实例
- 如何更改字符串/符号的所有实例的样式
- 替换字符串中YouTube/Vimeo iframe的所有实例
- 字符串是对象 String() 的实例吗?
- 我们如何在 javascript 对象中使用字符串名称存储创建 Backbone 视图的实例
- 如何匹配并返回一个字符串的多个实例,其中单个撇号可以包含在任何索引中
- Jquery:在一个字符串中查找所有实例模式,提示用户替换模式的所有实例,然后进行替换
- Ember.js:使用模型实例的路由获取模型实例的 url 字符串
- 如何在 JavaScript 中替换字符串中“+”的多个实例
- 查找字符串中单词所有实例的位置,在控制台中得到不需要的重复
- 正则表达式 Express 将反斜杠 的每个实例替换为字符串中的 u
- 按第三个实例拆分字符串
- 使用其他javascript删除字符串中某个字符的所有实例
- 删除多余的;#字符串中的实例