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

JavascriptStringSubstringSliceSubstr

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

id.slice(0, -2)

Solution 2 - Javascript

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

Solution 3 - Javascript

var str = "031p2";
str.substring(0, str.length-2);

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

Solution 4 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLoganView Question on Stackoverflow
Solution 1 - JavascriptTomalakView Answer on Stackoverflow
Solution 2 - JavascriptJames AllardiceView Answer on Stackoverflow
Solution 3 - JavascriptCyril N.View Answer on Stackoverflow
Solution 4 - JavascriptTom WadleyView Answer on Stackoverflow