How to delete last character from a string for instance in 123-4-
when I delete 4
it should display 123-
using jQuery.
The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
Use the String. replace() method to replace the last character in a string, e.g. const replaced = str. replace(/. $/, 'replacement'); .
slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
jQuery trim() method The trim() method is used to remove the space, tabs, and all line breaks from the starting and end of the specified string. This method does not remove these characters if these whitespace characters are in the middle of the string. The commonly used syntax of using this method is given as follows.
You can also try this in plain javascript
"1234".slice(0,-1)
the negative second parameter is an offset from the last character, so you can use -2 to remove last 2 characters etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With