在 TextArea 中保留换行符

问题描述 投票:0回答:1

我正在尝试删除文本中的特殊字符,但保留换行符。尽管问题已在这里得到解答保留文本区域中的换行符。然而,由于某些原因,它在我的情况下不起作用,这是一个文本区域。

//Javascript Part
let inputText = document.getElementById('inputTextArea').value;
let cleanedText = inputText
  .replace(/[^\w\s]/gi, function(match) {
    return match === '\n' ? '\n' : ' ';
  })
  .replace(/\s+/g, ' ') // Replace multiple spaces with a single space
  .trim(); // Remove leading and trailing spaces

// Set the cleaned text in the output textarea
document.getElementById('outputTextArea').value = cleanedText;
<textarea id="inputTextArea" rows="10" cols="50"></textarea>
<button class="clearButton" onclick="removeSpecialCharacters()">Clean Text</button>
<p>Cleaned Text:</p>
<textarea id="outputTextArea" style="white-space: pre-wrap; background: #90d9ab;" rows="10" cols="50" readonly></textarea>

javascript html css
1个回答
0
投票

@Barmar 用replace(/ +/g, ' ') 替换replace(/\s+/g, ' ') 的解决方案似乎有效。

© www.soinside.com 2019 - 2024. All rights reserved.