How to get substr of the string's all characters except for the last two digits? (ex: 031p2 >> get 031)

Logan picture Logan · Jun 10, 2011 · Viewed 40.3k times · Source
id = '01d0';
document.write('<br/>'+id.substr(0,-2));

How can I get the 01 without the last two chars? The trick is that if i do it like (0,2) it does get the first 2 numbers but this id will also be a three digit number... so I just need to get rid of the last two digits. This works with substr in PHP, how come (0,-2) doesn't work with javascript? More importantly how can i make this work?

Answer

Tomalak picture Tomalak · Jun 10, 2011

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

id.slice(0, -2)