views:

94

answers:

6

Can anyboyd help me split up this date number in javascript so that when it is outputted to the screen it has slashes between the 4th and 5th number and the 6th and 7th number, so that it can be understood by a vxml voice browser. The number can be any value so i need it to work for any eight digit number.

Like so:

20100820

2010/08/20

Many thanks

+4  A: 

If you have a simple string:

var a = '23452144';
alert(a.substring(0,4) + '/' + a.substring(4,6) + '/' + a.substring(6));

For a number, you can use

var s = a.toString();

For a long string with many such dates, this will replace their formats (you can easily play with it if you want a dd/mm/yyyy format, for example):

a.replace(/\b(\d{4})(\d{2})(\d{2})\b/g, "$1/$2/$3")
Kobi
when you borrow ideas from others' answers, it'd be nice to provide a credit (like "as per xxx's answer, you can also..."), don't you think?
stereofrog
@stereofrog - definitely. I've posted the string version before Pbirkoff. I was a little late with my regex, but decided to post it anyway because it's better (it is the only one that works on a string with multiple matches). The idea I copied any of it is a bold accusation, and I take offense at it.
Kobi
I think you're misunderstanding my comment, Kobi. This is nothing wrong with borrowing others' ideas as such - finally, we are here to share our thoughts and to learn from each other. But if do, it'd be nice to provide a credit, that it is.
stereofrog
A: 
var s = 20100820 + "";  // make the integer a string
var t = "";
for(var i=0; i<s.length; i++) {
    if(i == 4) // we're at the 4th char
        t += "/";

    if(i == 6) // we're at the 6th char
        t += "/";

    t += s.charAt(i);

}

console.log(t);
Luca Matteis
+3  A: 

You can use the substring-function for that. Assuming you always have the same input-format (eg. yyyymmdd), it can be done this way:

var dateString = "20100820";
var newValue = dateString.substring(0,4) + "/" + dateString.substring(4,6) + "/" + dateString.substring(6,8);

more on the substring function can be found at: http://www.w3schools.com/jsref/jsref_substring.asp

Pbirkoff
A: 
alert(20100820..toString().replace(/^(.{4})(.{2})/, "$1/$2/"))

PS. You need to accept some answers (see http://stackoverflow.com/faq for details).

stereofrog
That *PS* really should be a comment.
Kobi
A: 
var date ='20100317';
var output = date.replace(/(\d{4})(\d{2})(\d{2})/i,"$1/$2/$3");
alert(output);
Geln Yang
Eric - Welcome to Stack Overflow. You can format code by selecting it an clicking on the Code Button (101010). `<script>` will not help you here, but you could have used `<code>` and `<pre>` (same as you would in any website, when you think on it, you don't want to run the script...)
Kobi
+1  A: 

Use this javascript :

var objRegExp = /(\d{4})(\d{2})(\d{2})/;
var ourdate = "12334556";
var formateddate = ourdate.replace(objRegExp, "$1/$2/$3");

Now formateddate will have the require formatted date string.

pavun_cool