Reputation: 57
I'm trying to make a text editor where the user can change some text by highlight/select it and then click some button for delete or add a new char in it so I need to get that specific text
i have tried this window.getSelection().toString()
but my problem is that ifIi have text that have two or more same words like 'dont click here or here'
and the user highlighted the second 'here'
lets say then i cant really know which one of these two words the user has highlighted
so i want to get the highlighted string not by value or i don't know how do i solve this problem p.s. the text editor that i want to create is similar to this editor that i'm writing this question on
edit: my problem is not that i want to delete some string my problem is that i want to get the text not the value of the text so when i write 11111111111 and highlight only one of the 1s i can know exactly which one is highlighted
Upvotes: 0
Views: 62
Reputation: 29317
You could get the position of the selected text with getRangeAt()
Demo:
function getSel(el) {
console.clear();
var selObj = window.getSelection();
var selection = selObj.toString();
console.log(`Selected: ${selection}`);
var selRange = selObj.getRangeAt(0);
console.log(`from: ${selRange.startOffset}\nto: ${selRange.endOffset}`);
console.log(el.textContent);
el.textContent = `${el.textContent.substr(0, selRange.startOffset)} ***${el.textContent.substr(selRange.endOffset)}`;
};
<div onmouseup="getSel(this)">Lorem ipsum dolor sit amet, consectetur adipiscing elit Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
Upvotes: 0
Reputation: 2008
I have just tested with getSelection()
method and you can use baseOffset
& focusOffset
property to determine the position. BaseOffset counts & returns the number of character that the selection started & FocusOffset counts & returns the number of character where the selection end.
Here is an example:
function getHighLightText() {
let text = window.getSelection().toString();
console.log(text); // log selected text
//console.log(window.getSelection()); // log getSelection
console.log(window.getSelection().baseOffset + ' - ' + window.getSelection().focusOffset); // log selection start & end offset.
}
document.onselectionchange = getHighLightText;
<p id="p">111111111</p>
Note: Not tested with large text.
Upvotes: 1