Welcome to S-Design
The home of your bespoke, professional, fast-loading, interactive, database-driven web presence.


In the previous JavaScript Variables chapter, we showed you how to create a simple string variable.
We'll now show you a few things you can do with it.

To re-cap, here's a simply string variable: In Javascript, variables start with a "var" prefix if you want that variable to have global scope (accessible everywhere, even inside functions), or you can simply assign it. So "var hello" is a variable called "hello". To store data in that variable, we would simply say:
var hello = "Hi, my name is Simon";

There are lots of standard (built-in) functions in JavaScript dedicated to working with strings, so I won't list all of them, but here's a few I use all the time:

What if we wanted to join 2 string variables together? We need to concatenate them... concatenate means "to link together".
In JavaScript the concatenation operator (symbol) is the plus sign (+): <script>
text1 = "Hi, my name is Simon.";
text2 = "I'm very pleased to meet you!";
combined = text1+" "+text2;
This would make an alert pop-up with "Hi, my name is Simon. I'm very pleased to meet you!" inside it.
We've taken the variable text1 and concatenated it (joined it) to whatever is between the quote marks (in this case a space), and then concatenated (joined) variable text2 onto the end.

What if we wanted to know how long a string is: <script>
text = "Hi, my name is Simon.";
This would make an alert pop-up with "21" inside it.

What if we wanted to take a string and make it into an array: <script>
vegstring = "peas & carrots & parsnips & potatoes & broccoli";
veg=vegstring.split(" & ");
We would now have a array called veg that looked like veg=["peas","carrots","parsnips","potatoes","broccoli"];.

What if we wanted to take an array and make it into a string: <script>
vegstring=veg.join(" & ");
This would make an alert pop-up with "peas & carrots & parsnips & potatoes & broccoli" inside it.