我正在制作一個簡單的注釋框,我想通過僅用 1 個或 2 個標記替換空格來洗掉多余的空格,無論它們是換行符還是空格。
(\s){2,}是我到目前為止所擁有的。但是,我想讓用戶能夠將他們的評論加倍,并將其替換$1為第一個捕獲組,將他們的行減少到一個空格。
所以基本上,
如果我有 1 個空格或換行符,則將其替換為 1 個空格或換行符。
如果我有超過1 個空格或換行符,則將其替換為2 個空格或換行符。
謝謝。
uj5u.com熱心網友回復:
您可以使用
.replace(/(\s{2})\s /g, '$1')
詳情:
(\s{2})- 第 1 組:兩個空格字符\s- 一個或多個空格。
請參閱 JavaScript 演示:
const text = 'Abc 123\n DEF 234\n New line'
console.log(text.replace(/(\s{2})\s /g, '$1'));
uj5u.com熱心網友回復:
text=document.getElemntById('comment_text_input').value
while(text.indexOf('\n\n\n')!=-1||text.indexOf(' ')!=-1) {
text=text.replaceAll('\n\n\n','\n\n') //it makes '\n\n\n\n\n\n' to '\n\n\n\n', the next round '\n\n\n' and finally '\n\n'
text=text.replaceAll(' ',' ') // the same with the newlines
}
document.getElemntById('comment_text_input').value=text
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/463414.html
標籤:javascript 正则表达式
