[英]Get substring after first space and before first instance of a special character?
[英]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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.