除了最后两位数之外,如何获取字符串的所有字符的substr? (例如:031p2 >>获得031)

时间:2022-08-11 17:05:56
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?

如何在没有最后两个字符的情况下获得01?诀窍是,如果我这样做(0,2)它确实得到前2个数字,但这个id也将是一个三位数...所以我只需要摆脱最后两位数。这适用于PHP中的substr,怎么来(0,-2)不能用于javascript?更重要的是我如何才能完成这项工作?

4 个解决方案

#1


75  

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

您正在寻找slice()(另见MDC)

id.slice(0, -2)

#2


10  

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

尝试id.substring(0,id.length - 2);

#3


2  

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

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

请参阅:http://jsfiddle.net/GcxFF/

#4


1  

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.

substr的第一个参数是起始索引。第二个参数是要采用的字符数。

#1


75  

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

您正在寻找slice()(另见MDC)

id.slice(0, -2)

#2


10  

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

尝试id.substring(0,id.length - 2);

#3


2  

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

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

请参阅:http://jsfiddle.net/GcxFF/

#4


1  

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.

substr的第一个参数是起始索引。第二个参数是要采用的字符数。