You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现输入带""的内容时自动重复该内容?

实现输入框中双引号包裹内容的即时重复功能

基于你提供的自动大写代码,下面是修改后的完整实现,满足输入双引号包裹内容时即时重复该内容的需求,同时保留原有的大写转换功能,支持多次触发:

document.addEventListener('DOMContentLoaded', function(){
    let input_note = document.getElementById('note_text');
    input_note.addEventListener('input', handleInput)
})

function handleInput(ev){
    const input = ev.target;
    const cursorPos = input.selectionStart;
    let value = input.value.toUpperCase();

    // 匹配未被重复的成对双引号内容(避免重复处理已重复的内容)
    const regex = /(?<!")"([^"]+)"(?!")/g;
    // 将单个"内容"替换为"内容""内容"
    const newValue = value.replace(regex, '"$1""$1"');

    // 调整光标位置,避免修改内容后光标跳到末尾
    if (newValue !== value) {
        let offset = 0;
        let match;
        regex.lastIndex = 0; // 重置正则索引,避免遍历异常
        while ((match = regex.exec(value)) !== null) {
            const matchStart = match.index;
            const matchEnd = match.index + match[0].length;
            // 计算光标需要偏移的长度
            if (cursorPos > matchStart) {
                offset += match[0].length;
            }
        }
        input.value = newValue;
        input.setSelectionRange(cursorPos + offset, cursorPos + offset);
    } else {
        input.value = value;
        input.setSelectionRange(cursorPos, cursorPos);
    }
}

关键逻辑说明

  1. 保留大写转换:先将输入值转为大写,延续你原有代码的功能
  2. 精准匹配未重复内容:使用负向断言正则/(?<!")"([^"]+)"(?!")/g,只匹配前后没有引号的"内容",确保已重复的内容不会被再次处理(防止无限重复)
  3. 自动重复内容:将匹配到的单个"内容"替换为"内容""内容",输入完成闭合引号时立即生效
  4. 光标位置处理:记录并调整光标位置,修改输入值后光标不会跳到末尾,保证输入流畅性
  5. 支持多次触发:多个独立的双引号包裹内容会被分别处理,比如输入"a""b"会自动转为"A""A""B""B"

内容的提问来源于stack exchange,提问作者RoyKeane94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:09:25