- Home /
Find the length of a string in Javascript
I'm having tremendous difficulty trying to find the length of a string object that can vary as the host String (Not seen in the example) has different Strings split into an array that can be created/expanded in the hierarchy. Every time I try to find the length, it doesn't seem to work. The text object I'm making outputs onto a Textmesh. All the examples I saw of how to get a legnth either dealt with GUIText or finding the width of a GUI object as opposed to being based off of text. I don't want to do either of those. My goal is to print out text in a typewriter fashion, but every time the variable goes to a certain length, the array goes out of range and breaks the script. Is there a way to at least ignore an array once it goes out of range?
Heres what I got down for the typewriter text, at least the best I can interpret from.
var word:String = ("Test.");
var i:int =0;
var hostWord:String;
function Update()
{
hostWord += word[i];
i++; //Not the best way to add text of course, but this shows how quickly a letter can be added.
Debug.Log(hostWord); //Can also be seen in the hierarchy, but the debug window shows when it's been updated by every frame according to i++
}
Answer by DaveA · Mar 05, 2012 at 10:02 PM
word.Length would be that length.
Nowhere do you check for the length of the source, and incrementing i at 60+ frames per second will go over that limit quick.
Nowhere do you check for the length of the destination, I think you are assuming += will auto-expand the string's bounds, right? I'm not sure on that, you may need to allocate as you go, and don't allocate 1 byte at a time, it gets slow quickly. If you are creating long strings this way, pre-allocate the whole biggest chunk, or reallocate in, say, 1k chunks.
That's the thing. I'm not sure how to find the length.
I tried several methods.
[code]var strings1$$anonymous$$ax(text: String, charCount : int);[/code] This gives off several errors as if it can't compile the line.
I even tried to use a variable to obtain an amount of characters through these methods: [code]subtitles1Host += dialogue$$anonymous$$ode[npcID].dialogueSetptextString.subtitles1[i]; subtitles1Host += dialogue$$anonymous$$ode[npcID].dialogueSetptextString.subtitles1.Length;[/code]
However these also generate errors as well. I'm really not sure what to do to get variables. I even tried to create a variable named labels as well as Labels, but neither one work. What should I do?
Also as a side note, the string is being accessed through a class.
I think this will help: http://unifycommunity.com/wiki/index.php?title=AutoType
@Bartman3010: DaveA already told you how to get the length: word.Length
. Also, [code] tags don't work here, this site uses $$anonymous$$arkDown.
Ah. $$anonymous$$y apologies. Although after trying to use word.Length, it doesn't add up if it's out of the function groups. Putting it inside of the Update function causes the array to be out of range.