PDA

Click to See Complete Forum and Search --> : Length of Strings


richy
Feb 15th, 2001, 10:44 AM
In JavaScript how do you find the length of a string.
I've seen the way to do it is
stringname.length
but this always brings back an error.
I've also tried to do length(stringname) and Len(stringname).

Feb 15th, 2001, 11:01 AM
There's probably an easier way...but one thing that will work is to create a string object so you can use the length property. You could wrap this in a function to deal with other string values like this:

<HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function getLen(someString)
{
var str = new String();
str = someString;

return str.length;
}
// -->
</SCRIPT>
</HEAD>
<BODY LINK="#000080" VLINK="#000080">

<P><BUTTON onClick="alert(getLen('Hello World!'))">Click Me</BUTTON></P>

</BODY>
</HTML>

You could use a function like this to get the lengths of strings that weren't declared as string objects...like values from INPUTs or something.

Paul

richy
Feb 16th, 2001, 03:17 AM
This is a cut down version of my code.

var selvalue=s.value + "J";
For (N = 0; N<selvalue.length; N++)
{
}

and i keep getting the error of object expected. Maybe I've done something wrong in my loop, but whenever I take the loop out, the error disappears.

richy
Feb 16th, 2001, 03:26 AM
from doing a few tests now, I've found out it is my loop thats giving me the error, so can anyone tell me what's wrong with it?

P.S. I have declared N up above.

Feb 16th, 2001, 09:25 AM
I think you'd need to declare 'selvalue' as a string object to use the length property, as in the example I posted for you. I don't think a 'var' has the length property. That's probably why it's telling you that it's expecting an object.

Paul