Next page | Contents page |

String (and characters)

String

Text enclosed with single or double quotes.


  var name = "Fred"; // Using double quotes
  var courseName = 'JavaScript'; // Using single quotes
  var s1 = "This has a 'quoted' section in it."
  var s2 = 'So does "this".'
  var s3 = "Isn't this flexible?" // Note the apostrophe

As in C and Java, "escapes" can be used for special characters. Eg,

Strings are immutable: there is no way to change individual characters. Whatever you do to change a string actually creates a new one.

String concatenation

Only + has a special meaning for strings:
"7" + "3" is "73"

Therefore
"7" - "3" is 4 - how?

Answer: The - operator only works between numbers, so the system tries converting the 2 strings to numbers (and succeeds) before doing the subtraction.

var phrase = "Learning" + " " + "JavaScript";

If some arguments are numbers, they are converted to strings:


1 + 3       // adds numbers -> 4

"1" + "3"   // concatenates -> "13"

"1" + 3  // converts and 
         // concatenates -> "13"

However, + works from left to right unless parentheses are used,so

"Result = " + 120 + 4 gives "Result = 1204" but

"Result = " + (120 + 4) gives "Result = 124"

Characters and codes

JavaScript does not have a data type for single characters (unlike many other programming languages). To represent a single character you simply use a String of length 1. You can get such a string from any character position in another string by using the String function charAt(), remembering that counting begins at 0. Thus


  var s = "JavaScript";
  var ch = s.charAt (2); // ch is then "v"

You can get the numerical character code by using a similar function, charCodeAt().

Knowing some Unicode character codes you can also create a String from them by using String.fromCharCode (code1, code2, ...) (as many parameters as you need - we will see later how this is possible).

charCodeAt() and fromCharCode() enable you to encrypt strings according to any method you wish. We will find a use for this in providing data for the Hangman game.

Next page | Contents page |