Convert string into array

Hi there,

Is it possible to break apart a string into characters, be it a word or a sentence, and store each individual character in an array?

Thanks

In javascript you can split a string on any delimeter,
including the empty string, which splits the string between characters-

string=string.split(‘’);

Just to clarify, a string can be accessed just as if it were an array.


$char = 'Hello world!'[6] // w

Thanks for the help everyone.

Given that a string can be accessed as if it were an array, is it possible to loop through all the characters using a for loop? e.g.:

for (var i = 0, j = myString.length; i < j; i++) {
//do stuff to the selected character here
}

Yes it is, but it’s even easier in this case with a while loop.


$myString = 'Hello world!';
$i = 0;
while ($char = $myString[$i++]) {
    echo $char;
}
// shows "Hello world!"

Cool, that might solve my problem!

Thanks again for the help.

Yeh sorry Dan, took me a little while to get what you meant but I see now.

Thanks.

Right, so I think I have my loop working ok, however each alert comes up saying undefined instead of the letters in sequence. Do I need to declare myString as a new string or am I doing something else wrong?


<p id="first">This is my string</p>

<script language="JavaScript" type="text/javascript">
var myString = document.getElementById("first").innerHTML;
for (var i = 0, j = myString.length; i < j; i++) {
	alert(myString[i]);
}
</script>

Sorry if this is an easy one but I’m still very new to JS.

Thanks

It works fine in my browser, one character at a time in the alert boxes

Hmm that’s odd. I was trying it in IE so I’ll give it a go in something else. Thanks for letting me know.

It looks like we’ve come across a technique that works in all modern web browsers, but doesn’t in IE.

You will be safe using this instead:


alert(myString.substring(i, i + 1));

Great, that seems to have solved the issue in IE. Thanks for the solution.