[英]Add line break after meeting two conditions: Under "x" characters & ending with a comma or period
我正在做一個小項目。
該項目的目標是去除格式(雙空格、數字和換行符),然后 output 該值每隔“x”個字符換行一次,但確保它以逗號或句點結尾。
例如...如果我將字符限制設置為 50(在“until”中的“l”之后),我希望它看起來像下面這樣。 請注意,該示例傾向於使用標點符號而不是字符限制,但它不會添加換行符,除非您至少接近字符限制(我添加了額外的逗號以進一步解釋):
“敏捷的棕色狐狸跳過了懶狗,
直到那只狗,睡着了。”
而不是(字符限制):
“敏捷的棕色狐狸跳過懶惰的狗,直到
那只狗睡着了。”
或(標點符號):
“快,
棕色狐狸跳過懶狗,
直到那只狗,
睡着了。”
如果您希望我當前的代碼(刪除雙空格、數字和換行符)在...
<script>
function printText() {
var inputValue = document.getElementById("paste-text").value;
function editText() {
inputValue = inputValue.replace(/(\r\n|\n|\r)/g, ' ');
inputValue = inputValue.replace(/[0-9]/gm, ' ');
inputValue = inputValue.replace(/(\s\s\s\s)/gm, ' ');
inputValue = inputValue.replace(/(\s\s)/gm, ' ');
inputValue = inputValue.trim();
return inputValue;
}
if (inputValue.length > 0) {
document.getElementById("text-output").innerText = editText();
document.getElementById("edit-text-output").classList.add("showEdited");
}
}
</script>
<section>
<div class="edit-text-container">
<div class="edit-text-input">
<div class="edit-text-paste">
<h3>Paste Text</h3>
<div class="edit-text-input-area">
<textarea name="paste-text" id="paste-text" rows="6" placeholder="Paste Text Here"></textarea>
</div>
<input type="submit" value="Remove Formatting" onclick="printText()">
</div>
</div>
<div id="edit-text-output">
<h3>Your <i>edited</i> Text</h3>
<div class="edit-text-output-area">
<textarea readonly id="text-output" rows="6"></textarea>
</div>
</div>
</div>
</section>
<style>
textarea {
margin:0;
width:100%;
padding:16px; }
#edit-text-output {
height:0px;
overflow:hidden;
opacity:0;
transition: all 0.5s;}
.showEdited {
height:185px!important;
opacity:1!important; }
.edit-text-container {
justify-content:center;
text-align:center; }
input[type=submit] {
margin-top:16px; }
</style>
同樣,這是針對個人項目的,因此如果不可能,請不要急於尋求解決方案/沒問題。
我曾嘗試通過 Javascript 執行基本的 if/else 語句,但無濟於事。 我對 jQuery 和 Javascript 有基本的了解,所以我可能只是因為我缺乏知識而受到限制。
在查找解決方案后,我想出了如何在字符限制處創建換行符並在標點符號處創建換行符,但由於某種原因我無法弄清楚如何在標點符號處的換行符成為首選 function .
目前,它是內部矛盾的。
每一個“x”字符換行,但確保它以逗號或句點結尾。
您的需求描述存在幾個問題:
我認為您希望換行符嘗試一個字,不是嗎? 但是你沒有提到這一點。
如果單詞超過 50 個字符會怎樣?
“確保”這一說法與可能出現一段 50 個字符且沒有逗號或句點的情況相沖突。
你真的是說每一行都不能超過 50 個字符嗎? 如果有一個單詞超過 50 個字符,則必須將其拆分。 [想想如果 50 個字符的單詞剛好在逗號之前,您希望發生什么:您是希望逗號換行還是單詞拆分,或者該行加長到 51 個字符。 如果你想要最后一個,那么這條規則必須重新措辭。]
關鍵是要清楚你想要什么。 如果您可以明確地表達這一點,您通常可以很容易地對其進行編碼。 問題在於,在非編程世界中,大多數人在描述時都含糊其辭,直到我們開始編寫代碼時我們才意識到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.