2016-08-03 17 views
1

Regexがタスクに必要でない場合は使用しません。さんはsubstring Bそれを呼ぶことにしましょう、私は...部分文字列Bの最初のインスタンスの前に、部分文字列Aの最後のインスタンスを見つける方法はありますか?

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

をテキストエリアにテキストを持っている...と私は操作に興味があるテキストの行を選択しました。が存在する場合

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

は、私は、改行(\n)を見つけるのはsubstring Aそれを呼び出すようにしたい、それは、substring Bの前に来ます。見つけることで、私は文字列の改行のインデックスを取得することを意味します。

これはJS文字列関数で行うことができますか?これにRegexを使う必要がありますか?

+0

分割で分割し、興味のある行に達するまで、すべての部分の長さを加算します(各改行に1を加えます)。 – CBroe

+0

最初から* 'Substring B 'までのすべてを含む新しい部分文字列を作成し、その部分文字列を' substring A'で検索できますか? – Santi

+0

'string.indexOf(" \ n ")'は新しい行の位置を返します。開始位置に2番目の引数を渡すことができます。 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf – vlaz

答えて

2

substringBを見つけるには.indexOf()を使用し、次に.lastIndexOf()を使用して、そこから後方に検索するsubstringAを探します。 .indexOf().lastIndexOf()の両方には、オプションのIndex引数があります。

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をチェックしてください。

+0

これはそれを行う必要があります。他のコメントが示唆するように分割してカウントする必要はありません。それは無駄です。 – vlaz

+0

@ Vldと* *私が先に進んで頼んで、自分の無駄な解決策を試すのではなく、2分で*正しく*実行する方法を学ぶ理由です(私は尋ねる前に分割方法を試していました)。 –

関連する問題