...

View Full Version : Remove the last 16 digits at the end of text



Ruriko
11-26-2012, 10:25 AM
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?

devnull69
11-26-2012, 10:45 AM
You could use a regular expression


var n = str.match(/(.*)_\d{8}_\d{6}$/)[1];

Philip M
11-26-2012, 10:54 AM
Three other ways:-


<script type = "text/javascript">

var str="[APPLE PIE] Sei Shoujo Sentai Lakers 3 Battle Team Lakers 3 (100% FULL-PIC)_20121104_032834";
var str1 = str.replace(/(\)).*/i, "$1"); // assumes final character before digits is )
alert (str1);

var len = str.length;
var str2 = str.substring(0,len-16); // assumes digits length is always 16
alert (str2);

var str3 = str.replace(/[0-9\_]+$/gi, "");
alert (str3);

</script>

The third one is probably the best.

felgall
11-26-2012, 06:43 PM
That last option can be made two characters shorter as \d is the same as 0-9 and _ doesn't need to be escaped in that spot.


var str3 = str.replace(/[\d_]+$/gi, "");
alert (str3);

Philip M
11-26-2012, 06:56 PM
That last option can be made two characters shorter as \d is the same as 0-9 and _ doesn't need to be escaped in that spot.


var str3 = str.replace(/[\d_]+$/gi, "");
alert (str3);

Big deal! What, 2 whole characters? That could make a big difference to the speed of execution. :D
I always escape special characters for clarity.

Logic Ali
11-26-2012, 07:08 PM
That last option can be made two characters shorter as \d is the same as 0-9 and _ doesn't need to be escaped in that spot.


var str3 = str.replace(/[\d_]+$/gi, "");
alert (str3);
I'm surprised you didn't spot that the g & i flags are redundant.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum