Friday 20 March 2009

Convert a String to an ASCII / Unicode String with JavaScript

This JavaScript function converts a string of characters to a corresponding string of each characters unicode value.

function stringToAscii(s)
{
var ascii="";
if(s.length>0)
for(i=0; i<s.length; i++)
{
var c = ""+s.charCodeAt(i);
while(c.length < 3)
c = "0"+c;
ascii += c;
}
return(ascii);
}

If a characters unicode value is less than one hundred, zeros are prefixed to for that character, so that each original character has three digits in the returned unicode string.

And a test page

<html>
<head>
<script type="text/javascript">

function convertMe()
{
var converted = stringToAscii(document.getElementById('string').value);
document.getElementById('answer').innerHTML = converted;
}

function stringToAscii(s)
{
var ascii="";
if(s.length>0)
for(i=0; i<s.length; i++)
{
var c = ""+s.charCodeAt(i);
while(c.length < 3)
c = "0"+c;
ascii += c;
}
return(ascii);
}

</script>
</head>
<body>

<h1>String To ASCII/Unicode</h1>
<input id="string" type="text"/>
<input type="button" value="Convert" onclick="convertMe();"/>
<h1 id="answer"></h1>

</body>
</html>

068111110101.

Wednesday 11 March 2009

Javascript Function to Check Email Address Format using RegExp

This Javascript function performs a basic test to validate an email address.

The only true way of validating an email is to send an email and ask for a reply of some kind. This function is an initial step by making sure the format is correct.

function isEmail(e)
{
var emailPattern = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
return(emailPattern.test(e));
}

And an example html page.

<html>
<head>
<script>

function testEmail(e)
{
if(isEmail(e))
alert('true');
else
alert('false');
}

function isEmail(e)
{
var emailPattern = new RegExp(/^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/);
return(emailPattern.test(e));
}


</script>
</head>

<body>
<h1>Email RegExp Test</h1>
<input id="email" type="text"/>
<input type="button" value="Test" onclick="testEmail(document.getElementById('email').value);"/>
</body>

</html>

Validated.