69
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?

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Logan
  • 10,649
  • 13
  • 41
  • 54

4 Answers4

149

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

id.slice(0, -2)
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • 4
    The `slice()` is right. I'm always surprised by how few people know about it and its useful negative offsets. – Tim Down Jun 10 '11 at 09:53
11

Try id.substring(0, id.length - 2);

James Allardice
  • 164,175
  • 21
  • 332
  • 312
2
var str = "031p2";
str.substring(0, str.length-2);

See : http://jsfiddle.net/GcxFF/

Cyril N.
  • 38,875
  • 36
  • 142
  • 243
2

Something like:

id.substr(0, id.length - 2)

The first parameter of substr is the starting index. The second parameter is how many characters to take.

Tom Wadley
  • 121,983
  • 1
  • 26
  • 29