Javascript String operators
If you’d like to add two strings together, or concatenate them, you use the same + operator that you use for numbers:
var complete = "com" + "plete";
The value of complete will now be "complete".Again, you can use a combination of strings and string variables with the + operator:
var name = "Slim Shady";
var sentence = "Your name is " + name;
var sentence = "Your name is " + name;
The value of sentence will be "Your name is Slim Shady". You can use the += operator with strings, but not the ++ operator—it doesn’t make sense to increment strings. So the previous set of statements could be rewritten as:
var name = "Slim Shady";
var sentence = "Your name is ";
sentence += name;
var sentence = "Your name is ";
sentence += name;
If you try to add a number to a string, JavaScript will automatically convert the number into a string, then concatenate the two resulting strings:
var sentence = "I am " + 1977
sentence now contains " I am 1977".
sentence now contains " I am 1977".
1 comments:
The text of this section is stolen from the book, “Simply JavaScript” by Cameron Adams and Kevin Yank (or the online course, “JavaScript Programming for the Web”, which is based on that book).
Post a Comment