jQuery JavaScript


JavaScript prefix and suffix of a string

How to find prefix and suffix of the word in javascript

First of all, you have to know – how to get the currently selected text on the page by using the JavaScript. After that, I’ll show you how to get javascript prefix and suffix detection method of a string.

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.

How to get the currently selected text

function grabSelectedText() {
 var sel = null;

 if (window.getSelection) {
     sel = window.getSelection();
 } else if (document.getSelection) {
     sel = document.getSelection();
 } else if (document.selection) {
     sel = document.selection.createRange().text;
 }
 return sel;
}

Detail of currently selected text

Now, I am going to show you an example for getting start position, end position, prefix text, current text, suffix text and range of the text. By this function, you will definitely receive above all details.

function getSelectionDetail(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
     };
}

Get prefix String in javaScript

if(pre.length >= diff){
    pre = pre.substring(pre.length-diff, pre.length);
    pre = pre.substr(pre.indexOf(' '), pre.length);
}

Get suffix String in javaScript

if(post.length >= diff){
  post = post.substr(0, diff);
  post = post.substr(0, post.lastIndexOf(' '));
}

Similarly, with the help of the 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
     };

Conclusion

After that, the final code with the sample is here:

JavaScript prefix and suffix example

<!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 other technical information. We deliver 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 & services of 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 to 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 = getSelectionDetail(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 getSelectionDetail(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>

Published by Tirthraj Pandey

Professional Android app Developer, Full Stack Web Developer, Blogger, Entrepreneur And Founder of Coding Issue. I am always trying to learn new things or new possible ways to do things.

Did you find this page helpful?

X

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

*