Search code examples
javascripthtmlbrowsereditorwysiwyg

Surrounding selected text with tags


<ul class="contact">
<li class="first">Carnegie Mellon University</li>
<li>5000 Forbes Avenue, Pittsburgh, PA 15213</li>
</ul>

=>

<ul class="contact">
<li class="first">Carnegie Mellon University</li>
<li>[address]5000 Forbes Avenue, Pittsburgh, PA 15213[/address]</li>
</ul>

Imagine I open a web page in a browser and find some info useful in the page. So I'd like to select the useful info (e.g., the address of Carnegie Mellon University) from the page and click a TO-BE-IMPLEMENTED "inject tag" button. As a result, the source code of the page will be injected with a pair of tags (e.g., [address][/address]) surrounding the user selected text. Then I will save the injected source code for further processing.

Can anyone help suggest a way of implementing such a function? I'm really new to Javascript stuff so please be a little detailed with your suggestion.


Solution

  • Search in google, I find an example where you can get the selected text: http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html.

    With this, you only need to change the alert action to insert the tags you want. To do this with jquery, use the following code:

    $(selected).text("[tag]" + $(selected).text() + "[/tag]");
    

    where selected must be the variable that represents your selected text.