Javascript - 使用空格替代换行符

使用空格替代换行符

关键语句:

string.replace(/\u000A/g, ' ') // 使用空格替代换行符

示例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>使用空格替代换行符</title>
        <style type="text/css">
            * {
                font-family: "courier new";
                padding: 0;
                margin: 0;
                box-sizing: border-box;
            }
            div {
                width: 100%;
                height: 50vh;
                padding: 5px;
            }
        </style>
    </head>
    <body>
        <div>
            <textarea id="input" autofocus></textarea>
        </div>
        <div style="padding: 0 5px 5px;">
            <textarea id="output"></textarea>
        </div>
    </body>

    <script>
        window.onload = (event) => {
            const textareaInput = document.getElementById('input')
            const textareaOutput = document.getElementById('output')

            textareaInput.style = "width: 100%; height: 100%; padding: 5px;"
            textareaInput.placeholder = "input"

            textareaOutput.style = "width: 100%; height: 100%; padding: 5px;"
            textareaOutput.placeholder = "output"


            const regexp = /\u000A/g; // 换行符的 Unicode 编码
            const replacement = ' '; // 空格

            textareaInput.addEventListener('input', function(event) {
                textareaOutput.value = this.value.replace(regexp, replacement); // 使用空格替代换行符
            })

            textareaOutput.addEventListener('click', function(event) {
                // 选中所有字符
                this.selectionStart = 0
                this.selectionEnd = this.value.length

                document.execCommand('copy') // 复制选中的内容
            })
        }
    </script>
</html>

运行效果

在这里插入图片描述

参考

Window: load event

HTML 元素

document.getElementById()

document.querySelector()

Document Object Model (DOM)

Element

HTMLTextAreaElement

EventTarget.addEventListener()

Document.execCommand()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值