JQuery String Manipulation with substr method
From w3cyberlearnings
Contents |
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>
Related Links
String and Selector
- Manipulate String with substr method
- Manipulate String Style
- jQuery Selector
- Manipulate and Access String
- Manipulate JSON Data