Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this method work to assign characters, in JavaScript?

Ok, here goes a newbie question:

//function removes characters and spaces that are not numeric.

// time = "2010/09/20 16:37:32.37"
function unformatTime(time) 
{       

    var temp = "xxxxxxxxxxxxxxxx";

    temp[0] = time[0];
    temp[1] = time[1];
    temp[2] = time[2];
    temp[3] = time[3];
    temp[4] = time[5];
    temp[5] = time[6];
    temp[6] = time[8];
    temp[7] = time[9];
    temp[8] = time[11];
    temp[9] = time[12];
    temp[10] = time[14];
    temp[11] = time[15];
    temp[12] = time[17];
    temp[13] = time[18];
    temp[14] = time[20];
    temp[15] = time[21];   


}

In FireBug I can see that the characters from time are not assigned to temp? Do i have to use a replace() function to do something like this in JS?

Thank You.

like image 423
T.T.T. Avatar asked Sep 05 '25 03:09

T.T.T.


2 Answers

[^\d] is the regular expression for "not digit".

In more detail,

[] represents a "character class", or group of characters to match on.
\d is a shortcut for 0-9, or any digit.
^ in a character class negates the class.

function unformat(t)
{
   return t.replace( /[^\d]/g, '' );
}

You can't access a string like that in one of the major browsers, anyway. You would need to use str.charAt(x).

like image 89
Stefan Kendall Avatar answered Sep 07 '25 20:09

Stefan Kendall


You should definitely use a regular expression for this.

function unformatTime(time) {
    return time.replace(/[^\d]/g, '');
}

In this case it looks for anything that is a non-digit and replaces with an empty string. The 'g' at the end means "global" so it will replace as many times as it can.

  • ^ This inside the bracket means "not"
  • \d This means "digit"
  • g This means "global"
like image 36
Stephen Avatar answered Sep 07 '25 21:09

Stephen