Viziionary Viziionary - 4 months ago 12
Javascript Question

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

I'd like to not use Regex if it isn't necessary for the task. I've got some text in a textarea...

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


...and I've chosen a line of the text that I'm interested in manipulating, let's call it
substring B
.

var substringB = 're-throwing the exception since this approach stops propagating';


I want to find the linebreak (
\n
), let's call it
substring A
, that comes before
substring B
, if one exists. By find, I mean get the linebreak's index in the string.

Can this be done with the JS string functions? Do we need to use Regex for this?

Answer

Use .indexOf() to find substringB, then use .lastIndexOf() to find substringA searching backwards from there. Both .indexOf() and .lastIndexOf() have an optional fromIndex argument.

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>

Note: the simple code I've shown assumes that substringB will be found. You can add an if test to check that subBIndex != -1 if you want to explicitly test that before looking for substringA.