我有一个看起来像这样的字符串:
[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834
我想删除字符串末尾的数字,基本上是字符串末尾的16位数字。最后它应该是这样的:
[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)
这是我到目前为止编写的代码
var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834";
var n=str.substr(1,74);
document.write(n);
问题是字符串会有所不同,因此每个字符串都有不同的字符数。那么我如何删除javascript中字符串末尾的数字?
答案 0 :(得分:7)
如果字符串末尾总是正好是16位数字,那么:
s = s.substr(0, s.length - 16);
否则你可以使用regexp:
s = s.replace(/[_0-9]+$/, '');
答案 1 :(得分:2)
答案 2 :(得分:2)
使用slice
可以使用否定索引。
http://jsfiddle.net/gRoberts/A5UaJ/2/
var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834";
alert(str.slice(0, -16))
答案 3 :(得分:1)
只需更改代码即可根据字符串长度计算索引,以下代码应该可以解决问题。
myString.substr(0, myString.length - 16);
答案 4 :(得分:1)
以下是几个解决方案:
var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834";
// Solution 1
// Ugly, since you don't know the number of characters
var n = str.substr(0, 75); // Take note these variables are different than yours!
document.write(n);
document.write("<br />");
// Solution 2
// Only works when the string itself contains no underscores
var n2 = str.split("_")[0];
document.write(n2);
document.write("<br />");
// Solution 3
// Only works if the last amount of numbers are always the same
var n3 = reverse(str);
n3 = n3.substr(16, n3.length);
n3 = reverse(n3);
document.write(n3);
function reverse(s){
return s.split("").reverse().join("");
}
<强> JSFiddle 强>
答案 5 :(得分:0)
试试这个
var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834";
var find=str.indexOf('_');
find=find-1;
var n=str.substr(1,find);
document.write(n);
答案 6 :(得分:0)
检查此功能
检查示例 - http://jsfiddle.net/QN68Q/1/
<!DOCTYPE html>
<html>
<body onload="check();">
<script>
function check()
{
var theImg= "[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834";
var x = theImg.split("_");
alert(""+x[0]);
}
</script>
</body>
</html>
删除最后一个号码,这是你需要的吗?