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.

No comments: