JavaScript appears to be disabled. We recommend you enable JavaScript while visiting this site.

(All original content on this site is licensed under the Creative Commons License Attribution-Noncommercial-No Derivative Works 3.0.)

Function to Parse a Microsoft JSON DateTime returned from a WCF service in JavaScript

When a DateTime is converted to JSON in a WCF Web service (WebHttp in this particular case) it's semi-difficult to convert that to something we can use when we return the date to a client via JavaScript. For example:

"LastPlayed":"\/Date(1278187099000-0400)\/"

After almost an hour of research and goofing around with this, I've come up with the following, which seems to work just fine on Internet Explorer 8, Firefox 3.6, and Chrome 5.0.

function parseMicrosoftJsonDateTime(content) {
	try {
		content = content.replace(/\//g, '');
		var contentDate = eval('new ' + content);
		return contentDate.toDateString() + ' ' + contentDate.toTimeString();
	} catch (ex) {
		return content;
	}
}

As you can see if it fails at any point I just return whatever was passed. Otherwise since the only thing bothering us are the two /s, I'm first removing all of those. Then I'm creating a new variable, which ends up call new Date(x). This date variable can then be converted to a string via standard JavaScript functionality.

There may be a better way to handle this, but this is fairly quick, and works just as I need it to.

Sample outputs

Internet Explorer 8: Sat Jul 3 2010 14:58:18 CDT

Chrome 5.0 and Firefox 3.6: Sat Jul 03 2010 14:58:18 GMT-0500 (Central Daylight Time)

(All original content on this site is licensed under the Creative Commons License Attribution-Noncommercial-No Derivative Works 3.0.)

JavaScript object dump

I thought I posted this before, but I guess I did not.

Here's one way to dump a JavaScript object for analysis (if you don't have access to Firebug, or a similar tool).

Note it only dumps one level of data, and the code below is specifically for dumping an exception (catch ex), but swap ex in the three spots one spot with whatever object you'd like dumped.

var objectInfo = "";
// Change ex to whatever object you want to debug.
var objectToDebug = ex;
for (var prop in objectToDebug) {
	objectInfo += "property: " + prop + " value: [" + objectToDebug[prop] + "]\n";
}
objectInfo += "toString(): " + " value: [" + objectToDebug.toString() + "]";
alert(objectInfo);

I'm almost positive I found this code (pre-modifications) somewhere, but can't determine where that was (and having emailed myself this in December, lost my browsing history from that time). I've also updated the code to make use of variables, instead of the old method of adding the object to dump in a total of three spots.

And here's a function:

function dumpObject(o) {
	var objectInfo = "";
	var objectToDebug = o;
	for (var prop in objectToDebug) {
		objectInfo += "property: " + prop + " value: [" + objectToDebug[prop] + "]\n";
	}
	objectInfo += "toString(): " + " value: [" + objectToDebug.toString() + "]";
	alert(objectInfo);
}

Tags:

Categories: tutorials/guides

(All original content on this site is licensed under the Creative Commons License Attribution-Noncommercial-No Derivative Works 3.0.)

Regular Expression tester - JavaScript

In a previous post, I posted the code I used for a ColdFusion regular expression tester.

This time I've got an attempt at a JavaScript version. There's a number of TODOs, but ...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JavaScript Regular Expression Tester</title>
<style type="text/css">
 #form_help {
  float:right;
  font-size:.8em;
  width:50%;
 }
 #form_results {
  margin:1em;
  width:45%;
 }
 .highlight {
  background-color:#ff9;
 }
 #form_highlighttext {
  border:1px dashed #ccc;
  margin-left:1em;
  width:45%;
 }
</style>
<script type="text/javascript">
 function RemoveHTML(TextContent) {
  var str = '';
  str = TextContent;
  str = str.replace(/</g, "&lt;");
  
  return str;
 }
 function TestExpression() {
  var Expression = '';
  var ExpressionParameters = 'gm';
  var ExpressionText = '';
  try {
   document.getElementById('form_error').innerHTML = '';
   document.getElementById('form_results').innerHTML = '';
   document.getElementById('form_highlighttext').innerHTML = '';
   if (document.getElementById('InputExpression').value != '' && document.getElementById('InputText').value != '') {
    // TODO better check and error writing - use span with _s
    if (document.getElementById('CheckCase').checked) {
     ExpressionParameters += 'i';
    }
    Expression = document.getElementById('InputExpression').value;
    ExpressionText = document.getElementById('InputText').value;
    var ExpressionObject = new RegExp(Expression, ExpressionParameters);
    var ExpressionTest = ExpressionObject.test(ExpressionText);
    if (ExpressionTest == true) {
     document.getElementById('form_results').innerHTML = '<p>The following results were found for your search:</p>';
     // Testing it appears to run it, so ...
     ExpressionObject = new RegExp(Expression, ExpressionParameters);
     var StringPosition = 0;
     var LastPosition = 0;
     var CountResults = 0;
     var ExpressionResults = ExpressionObject.exec(ExpressionText);
     if (ExpressionObject.global) {
      while (ExpressionResults != null) {
       document.getElementById('form_results').innerHTML += '' + RemoveHTML(ExpressionResults[0]) + ' (' + ExpressionResults.index + ' - ' + ExpressionObject.lastIndex + ')' + '<br />';
       if (CountResults == 0) {
        StringPosition = 0;
       } else {
        StringPosition = LastPosition;
       }
       document.getElementById('form_highlighttext').innerHTML += RemoveHTML(ExpressionText.substring(StringPosition, ExpressionResults.index)) + '<span class="highlight">' + RemoveHTML(ExpressionText.substring(ExpressionResults.index, ExpressionObject.lastIndex)) + '</span>';
       LastPosition = ExpressionObject.lastIndex;
       ExpressionResults = ExpressionObject.exec(ExpressionText);
       CountResults++;
      }
      if (LastPosition && LastPosition < ExpressionText.length) {
       document.getElementById('form_highlighttext').innerHTML += RemoveHTML(ExpressionText.substring(LastPosition, ExpressionText.length));
      }
     } else {
      // TODO
      document.getElementById('form_results').innerHTML += '' + ExpressionResults[0] + ' (' + ExpressionResults.index + ')' + '<br />';
      document.getElementById('form_results').innerHTML += '<br /><br />';
      //document.getElementById('form_highlighttext').innerHTML += ExpressionText.substring(StringPosition, ExpressionResults.index) + '<span class="highlight">' + ExpressionResults + '</span>';
     }
    } else {
     document.getElementById('form_error').innerHTML = 'No match found.';
    }
   } else {
    document.getElementById('form_error').innerHTML = 'You must enter both an expression and text to check that expression against.';
   }
   return false;
  } catch(e) {
   alert(e.message);
  }
 }
</script>
</head>

<body>
 <div id="form_help">
  <p>Regular expression notation:</p>
  <ul>
   <li>\b = Word boundary</li>
      <li>\B = Word nonboundary</li>
      <li>\d = Numeral (0-9)</li>
      <li>\D = Nonnumeral</li>
      <li>\s = Single whitespace</li>
      <li>\S = Single nonwhitespace</li>
      <li>\w = Letter, numeral, underscore</li>
      <li>\W = Not \w</li>
      <li>. = Any character except newline</li>
      <li>[] = Any character(s) in brackets</li>
      <li>[^] = Not []</li>
      <li>* = Preceding zero or more times</li>
      <li>? = Preceding zero or one time</li>
      <li>+ = Precending one or more times</li>
      <li>{<em>n</em>} = The preceding <em>n</em> times</li>
      <li>{<em>n</em>,} = <em>n</em> or more times </li>
      <li>{<em>n</em>,<em>m</em>}= At least <em>n</em>, at most <em>m</em>, times</li>
      <li>^ = Beginning of the string or line </li>
      <li>$ = End of the string or line </li>
  </ul>
 </div>
 <form onsubmit="return false;">
  <label for="InputExpression">Regular expression:</label><input type="text" id="InputExpression" value="" /><br />
  <label for="CheckCase">Ignore case:</label><input type="checkbox" id="CheckCase" /><br />
  <textarea cols="50" id="InputText" rows="5">Hello and welcome. I do hope you'll come again. Will you?</textarea><br />
  <input type="button" onclick="TestExpression();" value="Test expression" />
 </form>
 <div id="form_error" style="color:red;"></div>
 <div id="form_results"></div>
 <div id="form_highlighttext"></div>
</body>
</html>

As always, comments appreciated.

Tags:

Categories: tutorials/guides