Slice in jQuery

jQuery provide slice method to cut your string according to your requirement. With the help of slice() method you can get any character at any position of your string.

Some examle of Slice method in jQuery

slice(-1) : Return last character
slice(-2) : Return last two character
slice(0, 1) : Return first character
slice(0, 2) : Return first tow character
slice(1) : Return all except first character
slice(2) : Return all except first two character
slice(0, -1) : Return all except last character
slice(0, -2) : Return all except last two character
slice(2, 3) : Return the third character
slice(2, 5) : Return the third to five character
CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnClick').click(function (event) {
        var name = $('.txtName').val();
        var result = ' slice(-1) : ' + name.slice(-1);
        result += '\n slice(-2) : ' + name.slice(-2);
        result += '\n slice(0, 1) : ' + name.slice(0, 1);
        result += '\n slice(0, 2) : ' + name.slice(0, 2);
        result += '\n slice(1) : ' + name.slice(1);
        result += '\n slice(2) : ' + name.slice(2);
        result += '\n slice(0, -1) : ' + name.slice(0, -1);
        result += '\n slice(0, -2) : ' + name.slice(0, -2);
        result += '\n slice(2, 3) : ' + name.slice(2, 3);
        result += '\n slice(2, 5) : ' + name.slice(2, 5);
        alert(result);
      });
    });
  </script>
</head>
<body>
   <div>
    <input type="text" class="txtName" value="Nirbhay Singh" /><br /><br />
    <button class="btnClick">Click</button>
  </div>
</body>
</html>
DISPLAY



2 comments :

  1. excellent tutorial thanks bro

    ReplyDelete
  2. excellent tutorial thanks bro...

    ReplyDelete