Javascript 内容可编辑文本被反转

Javascript 内容可编辑文本被反转,javascript,logic,contenteditable,Javascript,Logic,Contenteditable,遵循这个简单的逻辑,这里是一个非常简单的基于正则表达式的解析器 // Input: The **quick** brown fox **jumps** over the lazy dog let phrase = "The **quick** brown fox **jumps** over the lazy dog" // Operation phrase = phrase.replace(/(\*\*|__)(.*?)\1/g, "<strong>

遵循这个简单的逻辑,这里是一个非常简单的基于正则表达式的解析器

// Input: The **quick** brown fox **jumps** over the lazy dog
let phrase = "The **quick** brown fox **jumps** over the lazy dog"

// Operation
phrase = phrase.replace(/(\*\*|__)(.*?)\1/g, "<strong>$2</strong>")

// Output:  The <strong>quick</strong> brown fox <strong>jumps</strong> over the lazy dog
console.log(phrase)
问题:Hello World返回dlroW olleH,我的结果是相反的。这是如何修复的

const body=document.querySelector('body'))
常量编辑器=document.createElement('div')
editor.contentEditable='true'
editor.style.cssText='背景:浅蓝色;高度:50vh;宽度:50vw;'
editor.addEventListener('input',()=>{
editor.innerText=editor.innerText.replace(/(\*\*.\uuuuuuuuuuuuuuuuuuu1/g,“$2”)
})

body.appendChild(编辑器)
如果您想了解。每次替换contenteditable的innertext时,光标都会重置其位置,因此每次更改innertext时,您要做的是设置光标,这可以使用range界面实现

const body = document.querySelector('body')
const editor = document.createElement('div')

editor.contentEditable = 'true'
editor.style.cssText = 'background: lightblue; height: 50vh; width: 50vw;'

editor.addEventListener('input', () => {
    let v = editor.innerText.replace(/(\*\*|__)(.*?)\1/g, "<strong>$2</strong>");
        editor.innerText = v;
    var range = document.createRange(),
    sel = window.getSelection();
    range.setStart(editor.childNodes[0],v.length);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
})

body.appendChild(editor)
const body=document.querySelector('body'))
常量编辑器=document.createElement('div')
editor.contentEditable='true'
editor.style.cssText='背景:浅蓝色;高度:50vh;宽度:50vw;'
editor.addEventListener('input',()=>{
让v=editor.innerText.replace(/(\*\*.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;
editor.innerText=v;
var range=document.createRange(),
sel=window.getSelection();
range.setStart(editor.childNodes[0],v.length);
范围。塌陷(真);
选择removeAllRanges();
选择添加范围(范围);
})
body.appendChild(编辑器)
这不是完美的操控,但这正是你所要求的。

const body = document.querySelector('body')
const editor = document.createElement('div')

editor.contentEditable = 'true'
editor.style.cssText = 'background: lightblue; height: 50vh; width: 50vw;'

editor.addEventListener('input', () => {
    let v = editor.innerText.replace(/(\*\*|__)(.*?)\1/g, "<strong>$2</strong>");
        editor.innerText = v;
    var range = document.createRange(),
    sel = window.getSelection();
    range.setStart(editor.childNodes[0],v.length);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
})

body.appendChild(editor)