Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <textarea id="txt1" cols="80" rows="5">The quick brown fox jumps over the lazy dog</textarea>
- <script>
- function getTextAreaSelection(textarea) {
- var start = textarea.selectionStart, end = textarea.selectionEnd;
- return {
- start: start,
- end: end,
- length: end - start,
- text: textarea.value.slice(start, end)
- };
- }
- function detectPaste(textarea, callback) {
- textarea.onpaste = function() {
- var sel = getTextAreaSelection(textarea);
- var initialLength = textarea.value.length;
- var textBefore = textarea.value.slice(0, sel.start);
- var textAfter = textarea.value.slice(sel.end, textarea.value.length);
- window.setTimeout(function() {
- var val = textarea.value;
- var pastedTextLength = val.length - (initialLength - sel.length);
- var end = sel.start + pastedTextLength;
- callback({
- start: sel.start,
- end: end,
- length: pastedTextLength,
- text: val.slice(sel.start, end),
- selection: sel,
- before: textBefore,
- after: textAfter
- });
- }, 1);
- };
- }
- function validateURL(textval) {
- var urlregex = new RegExp(
- "^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
- return urlregex.test(textval);
- }
- var textarea = document.getElementById("txt1");
- detectPaste(textarea, function(pasteInfo) {
- // pasteInfo also has properties for the start and end character
- // index and length of the pasted text
- if (pasteInfo.text != null && pasteInfo.text.length > 0 && validateURL(pasteInfo.text)) {
- // Handle trailing spaces in selection (happens when the word was selected with double-click)
- while (pasteInfo.selection.text.length > 0 && pasteInfo.selection.text.charAt(pasteInfo.selection.text.length-1) == ' ') {
- pasteInfo.selection.text = pasteInfo.selection.text.substring(0, pasteInfo.selection.text.length-1);
- pasteInfo.after = " " + pasteInfo.after;
- }
- // Replace URL with [link] tag
- textarea.value = pasteInfo.before + "[url=" + pasteInfo.text + "]" + pasteInfo.selection.text + "[/url]" + pasteInfo.after;
- var newPosition = textarea.value.length - pasteInfo.after.length
- // if no text was selected for title, position cursor inside the [url] tag
- if (pasteInfo.selection.text.length == 0) {
- newPosition -= 6;
- }
- textarea.setSelectionRange(newPosition, newPosition);
- }
- });
- </script>
- <br>
- To test this feature, select any part of the text, and paste (Ctrl-V, or right-click + Paste) a valid URL.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement