id = '01d0'; document.write('<br/>'+id.substr(0,-2));
How can I take a string like '01d0and get the
01` (all except the last two chars)?
In PHP I would use substr(0,-2)
but this doesn't seem to work in JavaScript.
How can I make this work?
To get the last two characters of a string, call the slice() method, passing it -2 as a parameter. The slice method will return a new string containing the last two characters of the original string.
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.
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
You are looking for slice()
(also see MDC)
id.slice(0, -2)
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