0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[js]文字列から繰り返し出現する文字列の間を取得する

Posted at

やりたいこと:文字列から繰り返し出現する文字列の間を順番に取得する。

例:

  • 元の文字列: "あいうえおかきくけこさしすせそあいうえおかきくけこ2さしすせそ"
  • 抽出したいもの:'かきくけこ', 'かきくけこ2'
str = "あいうえおかきくけこさしすせそあいうえおかきくけこ2さしすせそ";
const before = "あいうえお";
const after = "さしすせそ";

stock = [];
while(1){
	// strの中のbeforeを前から検索
	const beforeIdx = str.indexOf(before);
	// strの中のafterを前から検索
	const afterIdx = str.indexOf(after);

	if (beforeIdx >= 0 && afterIdx >= 0) {
	    // 両方とも見つかったら中身を取り出す
	    const result = str.substring(beforeIdx + before.length, afterIdx);
	    // console.log(result);//"かきくけこ"
	    stock.push (result);
	    str = str.replace(result, "").replace(before, "").replace(after, "");
	}else{
		break;
	}
}
console.log(stock);//['かきくけこ', 'かきくけこ2']

正規表現を使いたかった。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?