How to find prefix and suffix of the word in javascript

Find start and end position of selected text

How to find prefix and suffix of the word in javascript

First of all, you have to know that how to get the currently selected text on the page by using the JavaScript. So, Javascript provided a method for retrieving the current selection of the page by using window.getSelection(). After fetching the current selection, suppose that we want to show that some prefix and suffix world (characters) of the selected text. In such a case, I have explored the above algorithm for getting the wrapped text of the selected text.

  

function surroundRange() {
    var obj = getSelectionCharOffsetsWithin(document.body);
    var pre = replaceHtml(obj.pre);
    var text = replaceHtml(obj.text);
    var post = replaceHtml(obj.post);
    var start = obj.start;
    var end = obj.end;

    var position = start + '~~' + end + '~~'+ pre + '~~'+ text + '~~' +post;
    alert(position);
}


function replaceHtml(text) {
    text = text.replace(/[^\w\s]/gi, '');
    text = text.replace(/[\n\r\t]/g, '');
    return text;
}

function getSelectionCharOffsetsWithin(element) {
     var start, end, pre = " ", text = " ", post = " ", diff;
     var sel, range, priorRange, rearRange;
     var max_limit = 200;
     if (typeof window.getSelection != "undefined") {
         range = window.getSelection().getRangeAt(0);
         priorRange = range.cloneRange();
         priorRange.selectNodeContents(element);
         priorRange.setEnd(range.startContainer, range.startOffset);
         rearRange = range.cloneRange();
         rearRange.selectNodeContents(element);
         rearRange.setStart(range.endContainer, range.endOffset);
         start = priorRange.toString().length;
         end = start + range.toString().length;
         text = range.toString();

         if(text.length < max_limit){
            diff = (max_limit - text.length)/2;
            pre = priorRange.toString();
            post = rearRange.toString();

            if(pre.length >= diff){
                pre = pre.substring(pre.length-diff, pre.length);
                pre = pre.substr(pre.indexOf(' '), pre.length);
            }
            if(post.length >= diff){
                post = post.substr(0, diff);
                post = post.substr(0, post.lastIndexOf(' '));
            }
         }else{
             text = text.substring(0, max_limit);
             text = text.substr(0, text.lastIndexOf(' '));
         }
     } 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,
         pre: pre,
         text: text,
         post: post,
         range: range
     };
}

 

With the help of above code you'll get the start and end position of the selected text.  By using this JavaScript code you'll get these important value:

return {
         start: start,
         end: end,
         pre: pre,
         text: text,
         post: post,
         range: range
     };

 

After all, the final code with the sample file is there:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Legend Blogs Example Page</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Abou Us</h2>
  <p>Legend Blogs is the blog website related to information technology as well as other related topics. Our mission is to provide the best online resources on programming, web development and others technical information. We deliver the useful and best tutorials for you. Legend Blogs has free programming tutorials covering Android, PHP, HTML, Javascript, Jquery and much more topics. Any visitors of this site are free to browse our tutorials, live demos and download scripts.
  </p>

  <h2>Terms & Conditions</h2>
  <p>By accessing this web site, you are agreeing to be bound by these web site Terms and Conditions of Use, all applicable laws and regulations, and agree that you are responsible for compliance with any applicable local laws. If you do not agree with any of these terms, you are prohibited from using or accessing this site. The materials contained in this web site are protected by applicable copyright and trade mark law.
  </p>

  <h2>Privacy Policy</h2>
  <p>Your privacy is very important to us so Legend Blogs respect visitors privacy and committed to protecting your privacy. The following statements describe the privacy policy of Legend BLogs. This privacy policy applied to the site and all products, contents & servicesof Legend Blogs which gives you the most powerful and secure online experience.
  </p>

  <h2>Personal Identification Information:</h2>
  <p>Legend Blogs requires user registration only for valid and serious users. Users are free to visit at Legend Blogs, navigate all its pages, read all tutorials, view demos and download scripts. We are collecting personal information when visitors fill out a form, subscribe our newsletter and try the tutorial demo at our site.
  </p>

  <h2>Cookies:</h2>
  <p>Legend Blogs uses cookies to enhance visitors experience and improve the speed of our site. We do not use cookies to collect any personal information or sensitive information.
  </p>
  <div style="text-align: center">
      <input type="button" value="Click me" onClick="surroundRange()" />
  </div>
</div>
</body>
<script>
$(body).mouseup(function() {
   alert("hello")
});

function surroundRange() {
    var obj = getSelectionCharOffsetsWithin(document.body);
    var pre = replaceHtml(obj.pre);
    var text = replaceHtml(obj.text);
    var post = replaceHtml(obj.post);
    var start = obj.start;
    var end = obj.end;

    var position = start + '~~' + end + '~~'+ pre + '~~'+ text + '~~' +post;
    alert(position);
}


function replaceHtml(text) {
    text = text.replace(/[^\w\s]/gi, '');
    text = text.replace(/[\n\r\t]/g, '');
    return text;
}

function getSelectionCharOffsetsWithin(element) {
     var start, end, pre = " ", text = " ", post = " ", diff;
     var sel, range, priorRange, rearRange;
     var max_limit = 200;
     if (typeof window.getSelection != "undefined") {
         range = window.getSelection().getRangeAt(0);
         priorRange = range.cloneRange();
         priorRange.selectNodeContents(element);
         priorRange.setEnd(range.startContainer, range.startOffset);
         rearRange = range.cloneRange();
         rearRange.selectNodeContents(element);
         rearRange.setStart(range.endContainer, range.endOffset);
         start = priorRange.toString().length;
         end = start + range.toString().length;
         text = range.toString();

         if(text.length < max_limit){
            diff = (max_limit - text.length)/2;
            pre = priorRange.toString();
            post = rearRange.toString();

            if(pre.length >= diff){
                pre = pre.substring(pre.length-diff, pre.length);
                pre = pre.substr(pre.indexOf(' '), pre.length);
            }
            if(post.length >= diff){
                post = post.substr(0, diff);
                post = post.substr(0, post.lastIndexOf(' '));
            }
         }else{
             text = text.substring(0, max_limit);
             text = text.substr(0, text.lastIndexOf(' '));
         }
     } 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,
         pre: pre,
         text: text,
         post: post,
         range: range
     };
}
</script>
</html>

 

Download this example:

Demo For Prefix and Suffix Text

 

You Must Read:

Top