【发布时间】:2022-09-23 19:01:44
【问题描述】:
例如:\"first line<br><br>Second line\" 应替换为 \"first line<br>Second line\"\"first line<br><br><br>Second line\" 应替换为 \"first line<br><br>Second line\"
等等...
我想要做的是使用正则表达式将字符串中的所有换行符替换为<br> 字符串中的\"str.replace(/(?:\\r\\n|\\r|\\n)/g, \'<br>\')\",但这会增加一个<br> 标签,因为当有人在他们按下的textarea 中输入时输入两次而不是一次换行。
代码:
<textarea style=\"width:200px;height:200px\" id=\"first\"></textarea>
<textarea style=\"width:200px;height:200px;\" id=\"second\"></textarea>
<button id=\"submit\">submit</button>
<script type=\"text/javascript\">
const firstTextArea = document.querySelector(\'#first\');
const secondTextArea = document.querySelector(\'#second\');
const submitBtn = document.querySelector(\'#submit\')
submitBtn.addEventListener(\'click\' , function(){
let str = firstTextArea.value.replace(/(?:\\r\\n|\\r|\\n)/g, \'<br>\');
secondTextArea.value = str;
})
</script>
-
正则表达式是错误的工具。
-
使用
DocumentFragment并使用标准 DOM 方法对其进行操作。
标签: javascript html regex