Javascript 如何获取字符串除最后两位数字以外的所有字符的 substr?(例如:031p2 >> 得到 031)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6304473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get substr of the string's all characters except for the last two digits? (ex: 031p2 >> get 031)
提问by Logan
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 也将是一个三位数……所以我只需要去掉最后两个数字。这substr
在 PHP 中有效,为什么(0,-2)
在 javascript 中不起作用?更重要的是我怎样才能做到这一点?
回答by James Allardice
Try id.substring(0, id.length - 2);
尝试 id.substring(0, id.length - 2);
回答by Cyril N.
var str = "031p2";
str.substring(0, str.length-2);
回答by Tom Wadley
Something like:
就像是:
id.substr(0, id.length - 2)
The first parameter of substris the starting index. The second parameter is how many characters to take.
substr的第一个参数是起始索引。第二个参数是要取多少个字符。