修改后的代码如下:

function addPureParentheses() { const text = keywordsTextarea.value; const start = keywordsTextarea.selectionStart; const end = keywordsTextarea.selectionEnd;

if (start === end) { return; // 没有选中任何文本,直接返回 }

let selectedText = text.slice(start, end);

// 如果选中文本等于 [] 或 () 中的任何一个单个字符,则直接返回,不进行后续操作 if (selectedText === '[' || selectedText === ']' || selectedText === '(' || selectedText === ')') { return; }

// 将选取范围内的方括号替换成方括号内的文本内容 selectedText = selectedText.replace(/[(.*?)]/g, "$1");

// 去掉选中文本中的方括号 selectedText = selectedText.replace(/[/g, "").replace(/]/g, "");

// 如果选取的文本范围内以空格或英文逗号和空格结尾,则需要将右括号放在空格或英文逗号之前 if (/\s$/.test(selectedText) || /,(\s)?$/.test(selectedText)) { const hasLeadingSpace = /^\s/.test(selectedText); const newText = text.slice(0, start) + (hasLeadingSpace ? " " : "") + "(" + (hasLeadingSpace ? selectedText.replace(/^\s+|\s+$/g, "") : selectedText) + ")" + (/,(\s)?$/.test(selectedText) ? ", " : " ") + text.slice(end); keywordsTextarea.value = newText; keywordsTextarea.setSelectionRange(start + (hasLeadingSpace ? 2 : 1), end + 1); // 将光标移动到新添加的圆括号后面 } else { const newText = text.slice(0, start) + "(" + selectedText + ")" + text.slice(end); keywordsTextarea.value = newText; keywordsTextarea.setSelectionRange(start + 1, end + 1); // 将光标移动到新添加的圆括号后面 }

// 清除右括号前面的逗号 const newText = keywordsTextarea.value.replace(/,)/g, ")"); const newStart = start - text.slice(0, start).length + newText.slice(0, start).length; keywordsTextarea.value = newText; keywordsTextarea.setSelectionRange(newStart, newStart); // 将光标移动到替换后的文本范围的起始位置

// 如果选取的文本范围内已经存在[]方括号框起来的,并且有:1.2这样的英文冒号后面跟着数字及小数点,则需要将其替换成空字符串 const selectedTextAfterReplacement = selectedText.replace(/:\d+(.\d+)?/g, ""); if (selectedTextAfterReplacement !== selectedText) { const newText = text.slice(0, start) + selectedTextAfterReplacement + text.slice(end); const newStart = start + selectedTextAfterReplacement.length - selectedText.length; keywordsTextarea.value = newText; keywordsTextarea.setSelectionRange(newStart, newStart); // 将光标移动到替换后的文本范围的起始位置 }

现在的这个代码还有有问题:逻辑又出问题了如我选取的金 转成了金 应该是金 才对啊 如我选取的 金转成了 金 应该是 金才对啊代码是:function addPureParentheses const text = keywordsTextareavalue; const start = keywordsTextareaselectionStart; const end = keywo

原文地址: https://www.cveoy.top/t/topic/e9bZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录