1

I wanted to split a string into individual characters for output, and I thought about using string.split("") to convert my string into an array, but I found that it wasn't necessary. Look at this:

<script type = "text/javascript" language = "Javascript">
var vx = "FGHIFKL"
for (var i = 0; var i<vx.length; i++)
{
document.write(vx[i]); // Outputs FGHIFKL
} 
</script>

It seems you can access strings as if they were arrays by using vx[0] without explicitly using str.split. Because vx[0] = F, vx[1] = G, etc. Is this syntax generally allowed, or even recommended for use in browsers? And how come this even works? I didn't know you could do something like this until today. Thanks in advance!

1
  • yes. string is treated as a character array, esp in ECMAScript 5. Commented Jan 16, 2014 at 7:00

3 Answers 3

2

Yup, you can use [] notation to pull individual characters out of JS strings.

Keep in mind that this doesn't work in the older IE's (7 definitely fails, and I believe 8 does as well).

You can use charAt for a cross-browser solution

"asdf".charAt(1) === "s";
Sign up to request clarification or add additional context in comments.

Comments

1

A String in JavaScript is a sequence of characters.

There are two ways to get to individual characters in a string.

  1. The charAt method: str.charAt(n)
  2. ECMAScript 5 introduced a way to treat strings as an array-like object: str[n]

On the other hand, split method returns a new array which is an array of strings separated into substrings. Interesting to note is the fact that if separator parameter to the split method is an empty string, the string is converted to an array of characters.

Comments

0

Reading numerical indicies of strings is a reliable feature of javascript as of ES5. These index properties are not quite the same as on arrays in that they are not writable or configurable. Check out the MDN page for strings and the ECMAScript Language Specification sections 15.5.5 and 15.5.5.2 for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.