Looking for the previous guiStuff?
It's still here, the content didn't go anywhere. You may want to check out this new guiStuff though -- It's rather informative.
References/Tutorials:
Intro Documents:
guiStuff:
::Stuff for the multi-spec coder;
Coding, formats, standards, and other practical things.
<!-- JavaScript
Strings Part 2: Methods
In Part 1 we covered the basics of Strings in JavaScript. The String Class provides you with a wide range of methods with which to analyze and manipulate strings. This article will cover these methods, with the exception of the String-Array methods, which have to do with Array manipulation, and will be covered in a separate article.You've already been introduced to one String method: The
chatAt() method, which returns the character in the String located at the index which is given to it as an argument.charCodeAt()
A closely related method tochatAt() is charCodeAt(), which does almost the same thing, except that it returns the character code, instead of the character itself. Here's an example:
var myStr = new String("Leaves actually do grow on trees");
alert(myStr.charCodeAt(0)); // alerts 76
In this example,
alert outputs 76, which is the character code for the uppercase 'L' character.contact()
Theconcat() method is used to concatenate, or, more specifically, append, another string to a given string. This method does not effect the original String, but returns a new one instead. In fact, this holds true for all String methods: They are all immutable, which means they never effect the contents of the Strings, but rather return a new value for you to work with.Here's how
contat() looks in action:
var myStr = new String("Leaves");
var anotherStr = myStr.concat(" actually do grow on trees");
alert(anotherStr); // alerts 'Leaves actually do grow on trees'
alert(typeof anotherStr); // alerts 'string'
Here,
concat() added a literal string to the String stored in the myStr variable. You can also give concat() a string stored in a variable, instead of a literal one, it doesn't matter, it won't effect either one. Note that typeof actually returned 'string' as the data type. That's the primitive string type, not the String Object. You can easily convert this back to a String Object if you wish, but it's important to note that concat() returns a primitive string, rather than a String Object.It's much more common, however, to see the
+ operator used for concatenating strings. It's vitually the same as the concat() method:
var myStr = new String("Leaves");
var anotherStr = myStr + " actually do grow on trees";
alert(anotherStr); // alerts 'Leaves actually do grow on trees'
alert(typeof anotherStr); // alerts 'string'
The result is the same. This doesn't mean that
concat() is useless, however -- there are highly nested situations where using the + operator would make for very unreadable code.indexOf() and lastIndexOf()
The String methodsindexOf() and lastIndexOf() actually search a String for a particular character. They each return the index of a character within a String. The difference between them is that indexOf() starts its search from the beginning of the String, while lastIndexOf() starts its search from the end of the String.Here's how
indexOf() works:
var myStr = new String("Gargantuan");
alert(myStr.indexOf("a")); // alerts 1
Within the String "Gargantuan", the first occurrence of the lowercase letter 'a' is at index
1 (the second letter in the string). However, if we were to use lastIndexOf() on the same String:
var myStr = new String("Gargantuan");
alert(myStr.lastIndexOf("a")); // alerts 8
Here,
alert outputs 8, which is the index of the last occurence of the lowercase letter 'a' (the 9th letter in the string).localeCompare()
ThelocaleCompare() method helps sort Strings in their alphabetical order. It takes one argument: The String with which to compare the current String to. It returns one of three values:- If the argument String comes after the String Object,
localeCompare() will return -1.- If the argument String comes before the String Object,
localeCompare() will return 1.- If the argument String is equal to the String Object,
localeCompare() will return 0.In practice:
var myStr = new String("green");
alert(myStr.localeCompare("red")); // alerts -1
alert(myStr.localeCompare("green")); // alerts 0
alert(myStr.localeCompare("blue")); // alerts 1
Note that
localeCompare() is case-sensetive in English implementations, and that lowercase letters come before uppercase ones. Here's an example:
var myStr = new String("A");
alert(myStr.localeCompare("a")); // alerts 1
alert(myStr.localeCompare("A")); // alerts 0
alert(myStr.localeCompare("b")); // alerts -1
Slice and SubString
The String Class provides you with two methods that are specifically designed to extract substring values. They are sometimes confused with one another because how they operate may seem similar (when they're observed 'in the wild', ie -- within a complete script). Their names areslice(), and substring(). There is also a third method, called substr(), but it has been deprecated in favor of the previously mentioned methods.It's easy to define the
slice() method after the substring() method has been covered, so we'll start with substring().
The substring() method takes either one or two arguments. The first argument defines at which index of the String it should 'start selecting' the substring. The second argument defines at which index of the String it should stop selecting the substring. The index at which the selection stops does not include the letter at that index. If the second argument is not given, it is assumed that substring() should keep selecting until the end of the string.Here's an example:
var myStr = new String("abcdefg");
alert(myStr.substring(3)); // alerts 'defg'
alert(myStr.substring(3, 5)); // alerts 'de'
alert(myStr.substring(0)); // alerts 'abcdefg'
alert(myStr.substring(0, 3)); // alerts 'abc'
The first time
substring() was called, it was given '3' as a first argument, and no second argument. It went to index 3 of the String, which held the letter 'd', and selected through to the end of the String. The second time, it was again given '3' as the first argument, but this time it was also given '5' as the second argument. It again went to index 3 of the String, and selected through to index 5, where it found the letter 'f', but it didn't include it, since by definition it's supposed to stop at index 5, and by doing so, it selected 2 letters: "de". This makes sense, since if you subtract '3' (the first argument) from '5' (the second argument), you get 2. It's like you're selecting 'from the 3rd index to the 5th index, not including the 5th'.The third time was the simplest one --
substring() was given one argument, '0', which basically meant selecting from the first letter in the String through to the end of the String. It simply returned the entire String. The fourth time it was given two arguments: '0', and '3'. This is very similar the the second instance, except this time, it's selecting from index 0 (the letter 'a'), through to, but not including, index 3 (the letter 'd'), so the resulting substring is "abc".Two scenarios come to mind with the arguments that
substring() takes. First, What happens if the first argument is bigger than the second argument? This is handled very 'neatly': they're reversed. Every time substring() sees two arguments, it will always consider smaller number to be the first argument. So, in a sense, if you give substring() two arguments, it doesn't matter in what order you place them... substring() will 'make it work' for you (in a sense).The second scenario is negative numbers. The
substring() method handles negative numbers very simply: every number less than 0 equals 0. Again, very 'neat', isn't it? If substring() sees that any argument that was given to it is less than 0, then it will convert it to 0.I should be clear that my writing 'neat' and 'neatly' isn't me being snarky, it's the purpose of the
substring() method to automatically 'avoid problems' when you choose to use it, as opposed to the slice() method which will consider every option, and, as a result, will allow many unwanted results if you choose to use it in the 'wrong' place. But we'll get to slice() in a bit.Here are some negative numbers:
var myStr = new String("abcdefg");
alert(myStr.substring(-3)); // alerts 'abcdefg'
alert(myStr.substring(-3, 5)); // alerts 'abcde'
alert(myStr.substring(3, -5)); // alerts 'abc'
The first one is converted to one argument, '0', and so returns the entire String. The second is converted to
substring(0, 5), and so returns 'abcde'. The third is first converted to substring(3, 0), and the arguments are reversed into: substring(0, 3), so you get: 'abc'.Now to the
slice() method. The function of the slice() method is exactly the same as the function of the substring() method, up to the point of reversed-sized numbers, and negative numbers. Now you can see why I chose so start with substring(). Here's slice() in action, with the exact same arguments as the first example of substring():
var myStr = new String("abcdefg");
alert(myStr.slice(3)); // alerts 'defg'
alert(myStr.slice(3, 5)); // alerts 'de'
alert(myStr.slice(0)); // alerts 'abcdefg'
alert(myStr.slice(0, 3)); // alerts 'abc'
There were no negative numbers, and the arguments were always given so that the first argument was smaller than the second, so
slice() produced the exact same results as substring().Now let's get to what makes
slice() different. Negative numbers are handled as if you're counting from the last character in the string. If your string is 7 characters long, and slice() received a '-1' in any of its two arguments, it will translate it to the last position in the string, or index 6. In other words, any negative number will be translated to the length of the String, minus that number. In JavaScript, you could say it would be myStr.length-myNum.Here are some examples:
var myStr = new String("abcdefg");
alert(myStr.slice(-3)); // alerts 'efg'
alert(myStr.slice(-5, -3)); // alerts 'cd'
alert(myStr.slice(0, -4)); // alerts 'abc'
alert(myStr.slice(4, -2)); // alerts 'e'
In the first example,
slice() was given only '-3' as an argument, so it took the length of the string (7), and subtracted 3 from it, getting '4'. This basically translated into slice(4), which produced 'efg'. In the second example, slice() received two negative numbers, and, using the same subtract-from-length method, it translated into (2, 4), which resulted in 'cd'. The third example is known as the "how many letters to chop?" method. This is where you give slice() '0' as the first argument, and a negative number as the second, resulting in a String missing that number of letters from its end. You'll see it quite often in parsing scripts where someone is "eating at a string from both ends" (the reverse of this is giving either slice() or substring() just one positive number as an argument, resulting in that String missing that number of letters from its beginning). The last example is just there so that there's one in which there's a positive number and a negative one. It just translates into (4, 5), which produces one letter: 'e'.Now there's a tricky part in
slice(): If you give slice() two arguments, both positive numbers, and the first argument is larger than the second argument, it's supposed to return an empty string. Actually, it doesn't matter if the numbers are positive, what matters is what slice() translates your arguments to, using the subtract-from-length method for negative numbers. Either way, if the end result is a larger number as the first argument, you're supposed to get an empty String, but this isn't written in stone. Whatever happens, your program won't 'crash' or anything, it's just that in some implementations of JavaScript you may get a different result. For example, there's a non-browser implementation in which slice() would mimick substring() if this happened, regardless of negative numbers (meaning it switches the two numbers). What this means isn't that you should avoid slice() -- far from it. It just means that you should consider the scenarios in which you're placing slice() beforehand, and decide on how to condition your code so that you know exactly which arguments each function and method will be presented with (this is often referred to at 'regulating arguments'). This is what I meant earlier when I said that substring() is 'neat' -- it handles odd situations for you. It's up to you to decide when to use which tool.toUpperCase() and toLowerCase()
As can be deduced from their names,toUpperCase() and toLowerCase() convert a String to all-uppercase and all-lowercase letters, respectively. However, several of the later releases of JavaScript (which actually include the large majority of JavaScript implementations you'll encounter these days, including any moderately-modern browser) also include toLocaleUpperCase() and toLocaleLowerCase(). These newer versions act exactly the same ways as their corresponding older versions, but are better-suited for use with unicode case conversions. Some languages treat upper-to-lower and lower-to-upper conversions differently than English does, and the original toUpperCase() and toLowerCase() were designed mainly for English, with some languages appended later. The bottom line is, there's virtually no reason not simply use the newer versions of the methods today, unless you're 100% certain that your program will only be used by English users, and you think that it might be parsed by an old JavaScript implementation that might not be aware of the newer versions.Finally, an example:
var myStr = new String("Don't Panic");
alert(myStr.toUpperCase()); // alerts 'DON'T PANIC'
alert(myStr.toLocaleUpperCase()); // alerts 'DON'T PANIC'
alert(myStr.toLowerCase()); // alerts 'don't panic'
alert(myStr.toLocaleLowerCase()); // alerts 'don't panic'
One last thing: If you copy and paste the above code into your IDE, and it doesn't color-code the
toLocale versions, don't panic... It'll still work in the browser.
Return to the JavaScript section, or go the to Main page.