如何用div索引替换div中的字符串

时间:2013-12-26 05:31:03

标签: javascript jquery

有没有办法在contenteditable属性设置为true的div中替换字符串?
例如:

<div id="editableDiv" contenteditable="true">
    the quick brown fox jumps over a lazy dog.
</div>

该功能必须执行以下操作:

Scenario 1: start index : 0, end index : 2 and replace string : *why*  
Result : why quick brown fox jumps over a lazy dog.  

Scenario 2: start index : 10, end index : 14 and replace string : *red*  
Result : the quick red fox jumps over a lazy dog.  

以下是我用来获得角色位置的功能:

function getCaretCharOffset() {
    var element = document.getElementById("editableDiv");
    var caretOffset = 0;
    if (typeof window.getSelection != "undefined") {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        caretOffset = preCaretRange.toString().length;
    }
    else if (typeof document.selection != "undefined" && document.selection.type != "Control")
    {
        var textRange = document.selection.createRange();
        var preCaretTextRange = document.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    console.log(caretOffset);
    return caretOffset;
}

这是工作jsFiddle

3 个答案:

答案 0 :(得分:2)

<p id="demo">Click the button to extract characters from the string.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str = "Hello world!";
var res = str.substring(1,4);
document.getElementById("demo").innerHTML=res;
}
</script>

答案 1 :(得分:1)

您可以使用substring()方法获取搜索字符串,并使用replace()方法替换它

<div id="sam" contenteditable="true">the quick brown fox jumps over a lazy dog
</div>
<button id="click">Click Me</button>

document.getElementById("click").addEventListener("click",function()
{
   var startIndex = 0;
   var endIndex = 2;
   var str = "why";
   var divStr = document.getElementById("sam").innerHTML;

   var searchStr = divStr.substring(startIndex,endIndex+1);

   document.getElementById("sam").innerHTML = divStr.replace(searchStr,str);
},false);

直播Demo

答案 2 :(得分:-2)

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
</div>

$('#one span').text('Hi I am replace');