Last Updated on December 18, 2020 by Roshan Parihar
In this tutorial, learn how to remove first character from the string on button click using jQuery. The short answer is to use substring()
or slice()
to remove the first letter from the string.
The tutorial removes only the 1st 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()
with argument ‘1’ 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 also use the jQuery slice()
to remove the first letter. This works same as substring()
and removes the first letter of the string. You need to first get the text content using text()
. After that, use the slice()
with argument ‘1’ to remove the 1st letter.
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 in the previous example.
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
I hope, you like this tutorial on how to remove the first letter from the string using jQuery.