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

Example -get first two characters

        <title>First two characters</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
                var greeting ="Morning";
                var a1 = greeting.substr(0, 2);
                $('div').html(a1); // Mo
        <div>TODO write content</div>

Example 2

  • Use alert() to test your own result.
<script type="text/javascript">
          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

<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"/>