Put tag round user selected text?

I need to get the user selected region of the text field, and then insert the <a> tags there.

I use this to get the user selected area:

 var textComponent = document.getElementById('article'); var selectedText; if (document.selection != undefined) { textComponent.focus(); var sel = document.selection.createRange(); selectedText = sel.text; } // Mozilla version else if (textComponent.selectionStart != undefined) { var startPos = textComponent.selectionStart; var endPos = textComponent.selectionEnd; selectedText = textComponent.value.substring(startPos, endPos) } 

Now I know that I can perform a string search for the text selected by the user and insert tags around it, but what happens if this text selected by the user appears twice in the text, for example.

Hello, goodbye.

If the user selects a second “you” for the link they want, surely replacing the string will put tags around each instance of “you”.

What is the best way to do this?

+6
source share
2 answers

You can use my jQuery plugin for this ( demo ):

 $("#article").surroundSelectedText('<a href="foo.html">', "</a>"); 

Alternatively, you can use the getInputSelection() function, which I published several times in Qaru, to get the start and end characters of the selection in all major browsers and then replace the string with textarea value :

 var sel = getInputSelection(textComponent); var val = textComponent.value; textComponent.value = val.slice(0, sel.start) + '<a href="foo.html">' + val.slice(sel.start, sel.end) + "</a>" + val.slice(sel.end); 
+5
source

Why shoot selected text? What you really need is the beginning / end of the positions that you need to reset in the tags.

 var textComponent = document.getElementById('article'); var selectedText; var startPos; var endPos; // the easy way if (textComponent.selectionStart != undefined) { startPos = textComponent.selectionStart; endPos = textComponent.selectionEnd; } // the hard way else if (document.selection != undefined) { textComponent.focus(); var sel = document.selection.createRange(); var range = document.selection.createRange(); var stored_range = range.duplicate(); stored_range.moveToElementText(textComponent); stored_range.setEndPoint( 'EndToEnd', range ); startPos = stored_range.text.length - range.text.length; endPos = startPos + range.text.length; } // add in tags at startPos and endPos var val = textComponent.value; textComponent.value = val.substring(0, startPos) + "<a>" + val.substring(startPos, endPos) + "</a>" + val.substring(endPos); 

IE code modified from this link .

EDIT: Check out Tim Down's comment on new lines. Also probably use its soltion because it is better.

+2
source

Source: https://habr.com/ru/post/916566/


All Articles