After discussing the absolute basics, it’s time to talk about arrays and strings in JavaScript. These are really important elements, and having mastered them we are ready to go to the next level.
Arrays and strings in JavaScript
At first we’ll take a look at text strings and basic methods of processing them. Afterwards we’ll discuss the arrays.
Personally I really like coding something related with strings and/or arrays.
The text is supported by the String class (type). This class allows us to create objects that contain strings; chars and subtitles. Also provides a lot of methods to operate on these strings:
anchor | replace |
big | search |
blink | slice |
bold | small |
charAt | split |
charCodeAt | strike |
concat | sub |
fixed | substr |
fontcolor | substring |
fontsize | sup |
indexOf | toLowerCase |
italics | toSource |
lastIndexOf | toUpperCase |
link | toString |
match | valueOf |
Example — working with strings:
var str = new String("Hi JavaScript!"); document.writeln("Our string: " + str.italics() + " has " + str.length + "chars length");
Using the dot operator we call the method of the String class, associated with our object (string).
The + operator is used to connect the strings. Of course in the context of String type. For the numbers it’s just operation of summation.
Example — split the string by a separator:
var tab = "ab-cd-ef-gh".split("-"); for (index in tab) { document.write(tab[index] + "<br />"); }
For example, such effect in PHP is reachable by the explode() function.
Example — operations on a string (then anchor method):
var str = new String("abc"); // puts str to the <a> markup: // <a name="myname">abc</a> var str = "abc".anchor("myname");
Methods for processing strings
Below we described frequently used methods of the String class:
– charAt — returns the character located within the index specified by the argument:
var c = "abc".charAt(1);
– charCodeAt — returns the character code:
var code = "abc".charCodeAt(1);
– concat — string concatenation:
var str1 = "A"; var str2 = "B"; var str3 = "123".concat(str1, str2); // result: 123AB