2016-04-29 6 views
0

選択したテキストの前後に特定の文字を削除します。 <ランダム>と< /ランダム>のようになります。は、私はテキストがある場合は、選択しtext.For例の前と後に、いくつかの特定のテキストを削除したいのjavascript

This is a sentence that i am writing. 

「文章」以外を選択すると、何も起こりません。 私は特定のテキストを選択する方法を知っていますが、特定のテキストの前後にテキストを削除する方法の次のステップはわかりません。可能でしょうか?

答えて

1

function replaceSelection() { 
 
    var sel, range, fragment; 
 

 
    if (typeof window.getSelection != "undefined") { 
 
     // IE 9 and other non-IE browsers 
 
     sel = window.getSelection(); 
 

 
     // Test that the Selection object contains at least one Range 
 
     if (sel.getRangeAt && sel.rangeCount) { 
 
      // Get the first Range (only Firefox supports more than one) 
 
      range = window.getSelection().getRangeAt(0); 
 
      var selectedText = range.toString(); 
 
      var replacementText = selectedText.replace(/&lt;\/?random>/, ''); 
 
      range.deleteContents(); 
 

 
      // Create a DocumentFragment to insert and populate it with HTML 
 
      // Need to test for the existence of range.createContextualFragment 
 
      // because it's non-standard and IE 9 does not support it 
 
      if (range.createContextualFragment) { 
 
       fragment = range.createContextualFragment(replacementText); 
 
      } else { 
 
       // In IE 9 we need to use innerHTML of a temporary element 
 
       var div = document.createElement("div"), child; 
 
       div.innerHTML = replacementText; 
 
       fragment = document.createDocumentFragment(); 
 
       while ((child = div.firstChild)) { 
 
        fragment.appendChild(child); 
 
       } 
 
      } 
 
      var firstInsertedNode = fragment.firstChild; 
 
      var lastInsertedNode = fragment.lastChild; 
 
      range.insertNode(fragment); 
 
      if (selectInserted) { 
 
       if (firstInsertedNode) { 
 
        range.setStartBefore(firstInsertedNode); 
 
        range.setEndAfter(lastInsertedNode); 
 
       } 
 
       sel.removeAllRanges(); 
 
       sel.addRange(range); 
 
      } 
 
     } 
 
    } else if (document.selection && document.selection.type != "Control") { 
 
     // IE 8 and below 
 
     range = document.selection.createRange(); 
 
     var selectedText = range.text; 
 
     var replacementText = selectedText.replace(/&lt;\/?random>/, '')   
 
     range.pasteHTML(replacementText); 
 
    } 
 
}
<div onmouseup="replaceSelection()"><p>This is a &lt;random>sentence&lt;/random> that i am writing<p></div>

関連する問題