I am trying to replace selected text with another text.
Consider following is the line of text.
Hello world.Good morning. Hello world. Good mornin
You could do it like this:
SEE DEMO
function swapSelection(swapText) {
var sel = window.getSelection ? window.getSelection() : document.selection.createRange();
if (sel != "") {
if (sel.getRangeAt) {
var range = sel.getRangeAt(0);
var newNode = document.createElement("span");
newNode.setAttribute('class', 'swapclass');
range.surroundContents(newNode);
} else {
sel.pasteHTML('<span class="swapclass">' + sel.htmlText + '</span>');
}
$('.swapclass').replaceWith(swapText);
}
}
$('button').click(function () {
swapSelection('night');
});
To get the current selection in HTML5, use the DOM Range API.
To edit the selection, the Selections API can be used.
See also: Where did the Text Selection API go?
If you use jQuery, then use the wrapSelection plugin