This returns highlighted text:
function getSelection(elem) {
var selectedText;
if (document.selection != undefined) { // IE
elem.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
} else if (elem.selectionStart != undefined) { // Firefox
var startPos = elem.selectionStart;
var endPos = elem.selectionEnd;
selectedText = elem.value.substring(startPos, endPos)
}
return selectedText;
}
$(document).on('mousedown', 'button', function(e) {
var selection = getSelection( $('#txtarea').get(0) );
alert(selection);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txtarea">this is a test</textarea>
<button>highlighted text</button>
Now I need to select adjacent character from selected/highlighted text. for example if his is a t is selected, then I need to get both t(L) and e (R) characters. How can I do that?
Try this one
function GetSelection() {
var selection = "";
var textarea = document.getElementById("myArea");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
selection = textarea.value.substring(textarea.selectionStart - 1, textarea.selectionEnd + 1);
}
} else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement();
if (rangeParent === textarea) {
selection = textRange.text;
}
}
if (selection == "") {
alert("No text is selected.");
} else {
alert("The current selection is: " + selection);
}
}
<body>
<textarea id="myArea" spellcheck="false">Select some text within this field.</textarea>
<button onclick="GetSelection ()">Get the current selection</button>
</body>
Get the value of the textarea using
var preview=document.getElementById("txtarea");
Get it's content using
var str=preview.value
The string to be matched
x="his is a t"
Using indexOf to get the character at which it starts
res=str.indexOf(x)
this returns 1
To find the character before it(check for res!=0)
str.charAt(res-1)
Returns "t"
For the last char
str.charAt(res+x.length)
Returns "e"
Related
I'm building a simple text editor and I start with basics - as user press enter and start a new line a want to insert br to the the second textbox. The second textbox is meant to send ready formatted text to the database. As of now I managed to copy data from first to second textbox as user typing. Hence, I want to disable viewing br in the first textbox. Is there a way not to display br in the first textbox but technically have it. Thank you in advance!
DEMO: https://jsfiddle.net/mxr7hz3p/
Textboxes:
<textarea type="text" id="first"></textarea>
<textarea type="text" id="second"></textarea>
JS:
$(function (){
$('#first').keyup(function (e){
if(e.keyCode == 13){
var curr = getCaret(this);
var val = $(this).val();
var end = val.length;
$(this).val( val.substr(0, curr) + '<br>' + val.substr(curr, end));
}})
});
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
}
else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$('#first').keyup(function(){
$('#second').val(this.value);
});
You can simplify the JS in the fiddle to do this
$('#first').keyup(function(){
var val = $(this).val();
val = val.replace(/\n/g, '<br />')
$('#second').val(val);
});
https://jsfiddle.net/t3vzgnp7/2/
I want to delete some particular text before and after the selected text.For example if the text is:
<p>This is a <random>sentence</random> that i am writing<p>
If the user selects text,it should remove <random> and </random> from the text and text will be like this.
This is a sentence that i am writing.
If the user selects anything other than 'sentence',nothing will happen.
I know how to select a particular text but i dont know the next step on how to remove text before and after a particular text.Is it possible?
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(/<\/?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(/<\/?random>/, '')
range.pasteHTML(replacementText);
}
}
<div onmouseup="replaceSelection()"><p>This is a <random>sentence</random> that i am writing<p></div>
If I select (highlight with mouse) bold text, I want to have <b></b> tags around it (the same goes for <i>, <span style="color:red">, <sup>, etc...).
The problem appears when You starting to select bold words inside all-bold sentence. Logically if I selected bold text - I want to copy bold text to other place. But if selection doesn't cross formatting tags I loose format info...
Here is working fiddle example: https://jsfiddle.net/xt557ov5/1/
Select just word BOLD in first line & press button.
Now select all second line, and press a button.
If you want even more magic - select just word LINE, exactly from first letter to the last (four letters no spaces around) - You also will get LINE without any bold formatting around it.
Snippet :
$('#extract').on('click', function() {
extract();
});
function extract() {
var str = getSelectionHtml();
str = str.toString().replace(/</g, "<").replace(/>/g, ">");
console.log(str);
$('#result').empty().append(str);
}
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" id="extract">Extract</button>
<br>
<br>
<div id="edit">
<br>
<b>Select here just word BOLD and press [Extract].</b>
<br>
<br>
<br>Now select all this <b>LINE</b>, and press [Extract].
</div>
<h4>Result:</h4>
<div id="result">
</div>
Maybe this would help: stackoverflow: Identify wether the selected text in a web page is bold or not
In order to apply it to your code I constructed this:
...
function selectionIsBold() {
var range, isBold = false;
if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
document.designMode = "on";
sel.removeAllRanges();
sel.addRange(range);
}
}
if (document.queryCommandState) {
isBold = document.queryCommandState("bold");
}
if (document.designMode == "on") {
document.designMode = "off";
}
return isBold;
}
function extract(){
var str = getSelectionHtml();
if(selectionIsBold()){
str= "<b>"+str.toString()+"</b>";
}else{
str = str.toString().replace(/</g, "<").replace(/>/g, ">");
}
$('#result').empty().append(str);
}
...
Note: selectionIsBold returns also true when thr text is "<strong>"-tagged. For other text formation checks (e.g <i>) change
isBold = document.queryCommandState("bold");
to
isBold = document.queryCommandState("italic");
I am trying to create jquery which will allow to highlight selected text by mouse including several selection (e.g. three separate sections). Currently I have the following code, but experienced the following issues with this code:
it allows single selection (while I would like to have a possibility to select first sentence, then third one and have them both marked independently).
as it works based on regexp'es, when I select single letter (e.g. 'a') all letters are selected.
styles (e.g. bold) are not preserved.
Please advise how I can improve this script to address above issues.
Thank you!
js code:
enableHighlights(".mainPane");
function enableHighlights(thisDiv) {
$(thisDiv).on("mouseup", function () {
var selectedText = getSelectionText();
var selectedTextRegExp = new RegExp(selectedText);
var text = $(this).text().replace(selectedTextRegExp, "<span class='red'>" + selectedText + "</span>");
$(this).html(text);
$('#selection').html(selectedText);
});
}
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().htmlText;
}
return text;
}
this is as close as I could get to the correct answer: DEMO
enableHighlights(".mainPane");
var sText=[],
sStart=[];
function enableHighlights(thisDiv) {
var initialHTML=$(thisDiv).html();
var theHTML='';
$(thisDiv).on("mouseup", function () {
var selectedText = getSelectionText();
var selectedRange=getSelectionRange($(thisDiv)[0]);
sText.push(selectedText);
sStart.push(selectedRange.start);
theHTML=initialHTML;
$.each(sText,function(i,v){
var selectedTextRegExp = new RegExp(v);
var usingHTML=theHTML.slice(sStart[i]-1);
var text = usingHTML.replace(selectedTextRegExp, "<span class='red'>" + v + "</span>");
theHTML=theHTML.slice(0,sStart[i]-1)+text;
});
$(this).html(theHTML);
$('#selection').html(selectedText);
});
}
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().htmlText;
}
return text;
}
function getSelectionRange(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
};
}
the only problem is when you try to select a bold and normal text together which I was unable to find a workaround!
UPDATE: apparently, the issue I've been experiencing only affects the first element in the selection.
JSFiddle: http://jsfiddle.net/NhQCR/
My code that does the selecting from the web page:
if (!window.TB) {
TB = {};
}
TB.Selector = {};
// http://stackoverflow.com/questions/5643635/how-to-get-selected-html-text-with-javascript
// and
// http://stackoverflow.com/questions/7690319/javascript-how-do-i-expand-a-user-selection-based-on-html-tags
TB.Selector.getSelected = function() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0);
var startEl = sel.anchorNode;
if (startEl != range.commonAncestorContainer) {
while (startEl.parentNode != range.commonAncestorContainer) {
startEl = startEl.parentNode;
}
}
var endEl = sel.focusNode;
if (endEl != range.commonAncestorContainer) {
while (endEl.parentNode != range.commonAncestorContainer) {
endEl = endEl.parentNode;
}
}
range.setStartBefore(startEl);
range.setEndAfter(endEl);
sel.addRange(range);
var container = document.createElement("div");
container.appendChild(sel.getRangeAt(0).cloneContents());
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
and how I get the selected text:
var selected_text = TB.Selector.getSelected();
unfortunately, as seen in the picture, this method for selecting text remove certain white space characters, and adds an empty div at the end of the selection
This is what the selection looks like on the webpage:
For those wondering: this is how I got the alert to show what it does:
start_index = $j(".text_container").html().indexOf($selected_text);
end_index = start_index + $selected_text.length;
alert(start_index + " to " + end_index + "\n" + $selected_text + "\n=====================================\n" + $j(".text_container").html());
Currently, the selection code will expand the selection to make sure there are no unmatched tags.
I want code that will get me exactly what is on the webpage, without removing / adding anything =\ I just don't know where to start =\
I can't reproduce the first issue, "empty space before 9", even when i use It might be due to charsets, or little greens guys too. Anyway, all my selections starts at the correct point.
For the second issue the <div></div> at the end, simply replace
range.setEndAfter(endEl);
by
range.setEndBefore(endEl);
This sounds sound as you select stuff in an array from 0 to length-1.