2

制限として 2 番目のパラメーターを取得できることはわかってsplitいますが、探しているものではありません。そして、しっかりした文字列区切り文字で分割して再度結合することで実行できることを私は知っています。

問題は、区切り文字が正規表現であり、一致するパターンの正確な長さがわかりません。

次の文字列を検討してください。

this is a title
--------------------------
rest is body! even if there are some dashes!
--------
---------------------
it should not be counted as a separated part!

これを使用して:

str.split(/---*\n/);

私は手に入れます:

[
  'this is a title',
  'rest is body! even if there are some dashes.!',
  '',
  'it should not be counted as a separated part!'
]

そして、これが私がなりたかったものです:(最初の出現で分割したい場合)

[
  'this is a title',
  'rest is body! even if there are some dashes.!\n--------\n---------------------\nit should not be counted as a separated part!'
]

この解決策は私が現在持っているものですが、それは最初に発生したものです。

function split(str, regex) {
    var match = str.match(regex);
    return [str.substr(0, match.index), str.substr(match.index+match[0].length)];
}

正規表現の n番目の出現で文字列を分割するために、任意の数nのソリューションを一般化する方法に関するアイデアはありますか?

4

1 に答える 1