How can I get the characters before AND after the selected text, and then remove them?
For example, when double clicking on the text, it will select the text, but not the backticks before and after. I want to then remove those backticks.
I have it where I can add characters to the selection, but when only selecting the text and not the extra characters, I do not know how to remove them.
$(document).on('click', 'button', function(e) {
var target = $(this).attr('class');
var str = window.getSelection();
var text = str.toString().trim();
var l = text.length;
if ($(str.baseNode).closest('.input').length > 0) {
switch (target) {
case 'test':
if ((text.charAt(0) != "`" && text.charAt(l - 1))) {
var replacementText = "`" + text + "` ";
} else {
var rid = text.replace(/`/g, '');
var replacementText = rid + ' ';
}
break;
}
formatSelection(str, text, replacementText);
}
});
// format with buttons
function formatSelection(str, text, replacementText) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(replacementText));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}
.input {
border: 1px solid #ccc;
padding: 10px;
}
p {
display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="test">format</button>
<div contenteditable="true" class="input">
`text`
</div>
from Get characters before and after selection and remove them
No comments:
Post a Comment