Last active
August 28, 2017 10:13
-
-
Save aokashi/20daa16dbb88cbe9ee9dd86a9fc64898 to your computer and use it in GitHub Desktop.
句読点がメッセージの末尾にきた場合、折り返さずに詰めるプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<link rel="stylesheet" href="style.css"> | |
<title>句読点を詰めるテスト</title> | |
<script src="script.js" type="text/javascript"></script> | |
</head> | |
<body> | |
<div id="message"> | |
</div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var string = "これは文字列のテストです。横幅16文字になると折り返しますが、折り返す次の文字が句読点だった場合は、その句読点を末尾に持ってきます。\n改行する場合は、どんな感じで動作するかも確かめてみましょう。"; | |
var message = string.split('\n'); | |
const MESSAGE_WIDTH = 16; | |
window.onload = function() { | |
var messageElement = document.getElementById("message"); | |
message.forEach((line, i) => { // 1行(改行付き) | |
var element = document.createElement("span"); | |
var count = 0; | |
var string = ""; // 1行(改行を除く)分の文字列を蓄える文字列変数 | |
var lineElement; | |
for (i = 0; i < line.length || count != 0; i++) { // 1文字 | |
console.log(i, line.length); | |
if (is2ByteChar(line.charAt(i))) { | |
count += 2; | |
} else { | |
count++; | |
} | |
string += line.charAt(i); | |
if (count >= MESSAGE_WIDTH * 2) { | |
console.log(string, i); | |
if (line.charAt(i + 1) === "。" || line.charAt(i + 1) === "、") { | |
string += line.charAt(i + 1); // 句読点の場合は句読点も加えてiを進める | |
i++; | |
} | |
lineElement = document.createElement("span"); | |
lineElement.style.display = "inline-block"; | |
lineElement.style.width = "100%"; | |
lineElement.textContent = string; | |
element.appendChild(lineElement); | |
string = ""; | |
count = 0; | |
} | |
} | |
messageElement.appendChild(element); | |
messageElement.appendChild(document.createElement("br")); | |
}, this); | |
}; | |
function is2ByteChar(char) { | |
return (char.match(/^[^\x01-\x7E\xA1-\xDF]+$/) !== null); | |
} // http://www.pori2.net/js/number/8.html |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { | |
font-family: monospace; | |
} | |
#message { | |
width: 20em; | |
} | |
.blank { | |
display: inline-block; | |
width: 1em; | |
visibility: hidden; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment