It is possible to extract the selected text and its position within the content using JavaScript. While there are no direct solutions for obtaining the text position from a <textarea>
, an insightful post on Stack Overflow offers a method to retrieve this information from a <div>
. Additionally, you can create a <div>
that mimics the appearance of a <textarea>
, as demonstrated in another Stack Overflow answer here. By merging these two approaches with some adjustments, it becomes feasible to manipulate text efficiently by utilizing the 'changeValue' function.
<html>
<style>
#main {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
</style>
<body>
<div id="main" contenteditable>Samudrala RamuSamu</div>
<input type="button" onclick="changeValue()" unselectable="on" value="Get selection">
</body>
<script>
function getSelectionCharOffsetsWithin(element) {
var start = 0, end = 0;
var sel, range, priorRange;
if (typeof window.getSelection != "undefined") {
range = window.getSelection().getRangeAt(0);
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof document.selection != "undefined" &&
(sel = document.selection).type != "Control") {
range = sel.createRange();
priorRange = document.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint("EndToStart", range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end,
value: range.toString()
};
}
function changeValue() {
var mainDiv = document.getElementById("main");
var sel = getSelectionCharOffsetsWithin(mainDiv);
var mainValue = mainDiv.textContent;
var newValue = mainValue.slice(0,sel.start) + mainValue.slice(sel.end) + sel.value;
mainDiv.textContent = newValue;
}
</script>
</html>