Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all except last 2 characters of a string?

id = '01d0'; document.write('<br/>'+id.substr(0,-2)); 

How can I take a string like '01d0and get the01` (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?

like image 725
Logan Avatar asked Jun 10 '11 09:06

Logan


People also ask

How do you return the last two letters of a string?

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.

How do I remove the last 3 characters of a 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.

How do I return only part of a 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.


1 Answers

You are looking for slice() (also see MDC)

id.slice(0, -2) 
like image 174
Tomalak Avatar answered Oct 07 '22 00:10

Tomalak