JQuery String Manipulation with substr method

From CoderLearner
Jump to: navigation, search

Manipulate string in jQuery

  • Get last or first character of a string

substr syntax

  • Without the END, will take the rest of the element
SELECTOR.substr(START,END);

Example -get first two characters

<html>
    <head>
        <title>First two characters</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script 
            type="text/javascript" 
            src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
        </script>
        <script type="text/javascript">
            $(document).ready(function(){
                var greeting ="Morning";
                var a1 = greeting.substr(0, 2);
                $('div').html(a1); // Mo
             
            });
        </script>
    </head>
    <body>
        <div>TODO write content</div>
    </body>

Example 2

  • Use alert() to test your own result.
<script type="text/javascript">
     $(document).ready(function(){
          var greeting ="01234567";
          var a1 = greeting.substr(0, 2);      //01
          var a2 = greeting.substr(0, 3);      //012
          var a3 = greeting.substr(3,2);       //34
          var a4 = greeting.substr(greeting.length-2); //67 get the last two chars
          var a5 = greeting.substr(greeting.length-4); //4567 get the last four chars
                
     });
</script>

<seo metagenerator="jquery tutorial" title="Jquery/Ajax" metakeywords="jquery greater,jquery gt, jquery lt, less then, odd jquery,jquery find element, even jquery,jquery event, jquery mouse click, jquery double click, jquery hover, jquery string, jquery array, jquery button, jquery attriubtes" metadescription="jquery button, jquery attriubte, jquery example, jquery tutorial, jquery sample"/>