我正在開發一個小型專案。
該項目的目標是去除格式(雙空格、數字和換行符),然後輸出該值,並每隔“x”個字符換行一次,但確保它以逗號或句點結尾。 p>
例如...如果我將字元限制設為 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 有基本的了解,所以我可能會因為缺乏知識而受到限制。
在查找解決方案時,我弄清楚瞭如何在字元限制處創建換行符並在標點符號處創建換行符,但由於某種原因,我無法弄清楚如何在標點符號處創建換行符最喜歡的功能。
在編寫下一部分程式碼之前,請確保您的要求明確
目前,這是內部矛盾的。
您的需求描述有幾個問題:
我認為您希望換行符號能夠表達一個單詞,不是嗎?但你還沒提到這一點。
如果單字長度超過 50 個字元會怎麼樣?
「確保」語句與可能存在不帶逗號或句點的 50 個字元的可能性相衝突。
您的意思是每行長度不得超過 50 個字元嗎?如果單字長度超過 50 個字符,則必須將其拆分。 [考慮一下如果 50 個字元的單字就在逗號之前,您希望發生什麼:您希望逗號換行還是單字拆分,或者將行延長到 51 個字元。如果您想要最後一個,則必須重新措詞此規則。 ]
我建議像這樣列出要求:
如果上述內容是您想要完成的,那麼它就是編寫程式碼的良好基礎
關鍵是要清楚自己想要什麼。如果您能夠明確地表達這一點,那麼您通常可以輕鬆地對其進行編碼。問題在於,在非程式設計世界中,大多數人的描述都含糊不清,直到我們開始編寫程式碼時才意識到這一點。