Skip to content

Instantly share code, notes, and snippets.

@think49
Last active January 28, 2018 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save think49/9ccf52aa1f2d01e4417b6f0fb2d37ce9 to your computer and use it in GitHub Desktop.
Save think49/9ccf52aa1f2d01e4417b6f0fb2d37ce9 to your computer and use it in GitHub Desktop.
delete-duplicate-line.js: 文字列における重複行を削除する

delete-duplicate-line.js

概要

複数行を持つ「String 型の文字列」に対し、重複した行を削除します。

使い方

deleteDuplicateLine( string )

第一引数に指定されたString型の文字列から、重複行を削除します。 (※重複判定の対象は「**改行コードを除く文字列」**であり、行末の改行コードも合わせて削除されます)

console.log(deleteDuplicateLine('aaa\naaa')); // "aaa"

改行コードは、"CRLF", "CR", "LF" のいずれかも対応します。

console.log(deleteDuplicateLine('@aaa\n@aaa\r@aaa\r\n@aaa')); // "@aaa"

重複行は前方から検索していき、マッチした行から削除していきます(つまり、残されるのは一番最後に存在する重複行です)。

console.log(deleteDuplicateLine('@aaa\n@bbb\n@ccc\n@aaa\n@ddd\n@bbb\n@eee\n@aaa')); // "@ccc\n@ddd\n@bbb\n@eee\n@aaa"

RegExp Lookbehind Assertions (?<=pattern), (?<!pattern)

RegExp Lookbehind Assertions とは日本語で「後読み」と呼ばれる機能であり、「消費済の文字列に後からマッチさせる」性質があります。 「後読み」は2018/01/28現在、次の状況です。

  • ECMAScript 2018 では stage 4 (ECMAScriptへ取り込まれる準備が完了したことを示す状態)で定義されていますが、ECMAScript 2018 はまだ正式版ではありません
  • Google Chrome 62 で使用できます(先行仕様の実装)
  • Firefox, Safari, IE11, Microsoft Edge で使用できません
/**
* delete-duplicate-line-0.2.1.js
* Delete duplicate line.
*
* @version 0.2.1
* @author think49
* @url https://gist.github.com/think49/9ccf52aa1f2d01e4417b6f0fb2d37ce9
* @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
*/
'use strict';
function deleteDuplicateLine (string) {
return string.replace(/^(.*)(?:\r\n|[\n\r])(?=(?:(?!\1(?:[\n\r]|$)).*(?:\r\n|[\n\r]))*\1$)/mg, '');
}
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>test</title>
<style>
</style>
</head>
<body>
<script src="delete-duplicate-line-0.2.1.js"></script>
<script>
'use strict';
function deleteDuplicateLineToJSON (string) {
return JSON.stringify(deleteDuplicateLine(string));
}
console.assert(deleteDuplicateLine('@aaa\n@aaa\r@aaa\r\n@aaa') === '@aaa');
console.assert(deleteDuplicateLine('@aa\n@aaa') === '@aa\n@aaa');
console.assert(deleteDuplicateLine('@aaa\n@bbb\n@ccc\n@aaa\n@ddd\n@bbb\n@eee\n@aaa') === '@ccc\n@ddd\n@bbb\n@eee\n@aaa');
console.assert(deleteDuplicateLine('@みかん\n@みかんジュース\n@みかん\n@みかん\n@みかん\n@りんご\n@りんご\n@みかんジュース') === '@みかん\n@りんご\n@みかんジュース');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment