Skip to content Skip to sidebar Skip to footer

Removing The Last Digits In String

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 str

Solution 1:

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]+$/, '');

Solution 2:

Instead of substr, use replace and a regular expression:

str.replace(/_\d{8}_\d{6}/,'')

Running demo here.

References at MDN here.

Solution 3:

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))​

Solution 4:

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); 

Solution 5:

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 charactersvar 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 underscoresvar n2 = str.split("_")[0];
document.write(n2);
document.write("<br />");

// Solution 3// Only works if the last amount of numbers are always the samevar n3 = reverse(str);
n3 = n3.substr(16, n3.length);
n3 = reverse(n3);
document.write(n3);

functionreverse(s){
    return s.split("").reverse().join("");
}​

JSFiddle.

Post a Comment for "Removing The Last Digits In String"