|
Helping ordinary people create extraordinary websites! |
JavaScript StringsStrings form an essential part of JavaScript development. Almost all scripts will have to deal with strings at some point. Here we will cover some advanced concepts of strings that may be useful in building your application. Joining StringsThe process of joining strings is called string concatenation. Using the + symbol, a string can be joined to another string to produce yet another string. Consider this example: var string1 = 'Here is '; Joining a string is easy and straightforward, however has to be done carefully. The + symbol clashes with the mathematical addition operator, and in the case of a string of numbers, JavaScript carefully chooses between one of the two operations - joining strings or adding numbers - depending on the web browser. Here's an example: var firstvar = 200; Depending on your browser configuration, this could do one of three things. Firstly, it could (and hopefully will) output "200300". JavaScript dynamically converts the 200 to the string "200" so that it can be joined to another string. This is an example of JavaScript being weakly typed: the type of a variable doesn't really matter, because JavaScript will make the adjustments needed for your code to keep working. However, in some situations, this will output the number 200300. This is not a good idea, as this is now the number 200,300 - or two hundred thousand and three hundred. This behaviour is probably not what you want. However, if you do in fact want to chain strings containing whole numbers together, use Math.floor() which will, in this situation, simply convert the string to an integer: var firstvar = 20, secondvar = "30"; The third potential outcome of the previous example is that the
script will fail. This is highly unlikely, but is something to watch
out for. Your variable will be set to Joining a string containing letters to an integer should function identically, except that you will not receive an integer result. Detecting a stringSometimes you want to check if a variable is indeed a string (or any other type). This can be achieved with the JavaScript typeof construct. Simply prepend it to a variable name for the expression to evaluate to the type of that variable, like so: somevar = "Hello World!"; This will produce an alert box with the text "string". You can also use
|
|