In this tutorial, learn how to remove first character from the string on button click using jQuery. The short answer is to usesubstring()
or slice()
to remove the first letter from the string.
The tutorial removes only the first character from the string. You have to pass 1 as the argument of the function to remove the first letter of the string with jQuery.
jQuery Substring() to Remove First Character
To remove the first letter from the string, you can use jQuery substring(). You have to first use the jQuery text() to get the text content. After that, you have to use the substring first to remove the first letter of the string.
1 2 3 4 5 6 7 8 9 10 11 12 | <script> $(document).ready(function(){ $('#btnRemoveFirstSub').click(function(){ var myTextSub = $('.MyStringSub').text(); var RemoveFirstCharSub = myTextSub.substring(1); $('.removedStringSub').html('<strong>The new string is: </strong>'+RemoveFirstCharSub); }); }); </script> <p class="MyStringSub">&This is my string</p> <button type="button" id="btnRemoveFirstSub">Click me to Remove First Character</button> <p class="removedStringSub"></p> |
Output
&This is my string
The above example contains the ‘&’ symbol as the first character. Click the above button to remove the ‘&’ letter from the string. You will get the string without the first letter of the string.
Delete First Character Using Slice()
In addition to the above example, you can remove the first letter using slice(). This works same as substring() and removes the first letter of the string.
1 2 3 4 5 6 7 8 9 10 11 12 | <script> $(document).ready(function(){ $('#btnRemoveFirstSlice').click(function(){ var myTextSlice = $('.MyStringSlice').text(); var RemoveFirstCharSlice = myTextSlice.slice(1); $('.removedStringSlice').html('<strong>The new string is: </strong>'+RemoveFirstCharSlice); }); }); </script> <p class="MyStringSlice">&This is my string</p> <button type="button" id="btnRemoveFirstSlice" class="btn btn-primary">Remove First Character</button> <p class="removedStringSlice"></p> |
Output
&This is my string
Click the above-given button to remove the first letter of the string. This gives you the same string as you got with the substring() of jQuery.
You may also like to read.
- Remove All White Spaces from a string using jQuery
- Remove special characters from a string using PHP
- How to remove a single character from a string using jQuery
Hope, you like this tutorial on how to remove the first letter from the string using jQuery. If you have any query regarding the tutorial, please comment below.
Also tell me, which method you are using to remove the first letter from a string using jQuery.