Reputation: 179
I have a string that looks like this:
[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834
I want to remove the digits at the end of the string, basically the 16 digits at the end of the string. In the end it should look like this:
[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)
This is my code that I have written so far
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);
The problem is the string will be different so each will have different amount of characters. So how I remove the digits at the end of the string in javascript?
Upvotes: 2
Views: 4715
Reputation: 1114
Check this function
Check Example - 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>
it remove last numbers , is this what you required ?
Upvotes: 0
Reputation: 6394
Using slice
you can use negative indexes.
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))
Upvotes: 2
Reputation: 4539
Try this
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);
Upvotes: 0
Reputation: 6110
Here are a couple of solutions:
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("");
}
Upvotes: 1
Reputation: 5213
Instead of substr
, use replace
and a regular expression:
str.replace(/_\d{8}_\d{6}/,'')
Running demo here.
References at MDN here.
Upvotes: 2
Reputation: 3061
just change your code to calculate the index according to the string length the following code should do the trick.
myString.substr(0, myString.length - 16);
Upvotes: 1
Reputation: 22943
If it is always exactly 16 digits in the end of the string then:
s = s.substr(0, s.length - 16);
Otherwise you can use regexp:
s = s.replace(/[_0-9]+$/, '');
Upvotes: 7