Tuesday, June 03, 2008

Javascript Regular Expression to match a comma delimited list

This example uses the JavaScript String's match() method to parse a comma delimited list into a JavaScript array.


<html>
<head>
<script>
var str = "completeurl, debug, foo";

var m = str.match(/\w+(,\w+)*/g);

var count = m.length; // the count

function parseit() {
document.getElementById("_output").innerHTML="Total length:"+m.length+" ";
for(var i = 0; i < m.length; i++) {
document.getElementById("_output").innerHTML+="Token:\'"+m[i]+"\' ";
}
}
</script>
</head>
</html>
<body onload="parseit();">
<div id="_output" name="_output" style="border:1px solid black"> </div>
</body>
</html>

No comments:

Labels

Blog Archive

Contributors