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:
<script>
var hello = "Hi, my name is Simon";
</script>
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>
This would make an alert pop-up with "Hi, my name is Simon. I'm very pleased to meet you!" inside it.
text1 = "Hi, my name is Simon.";
text2 = "I'm very please to meet you!";
combined = text1+" "+text2;
alert(combined);
</script>
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.
<script>
text = "Hi, my name is Simon.";
alert(text.length);
</script>
This would make an alert pop-up with "21" inside it.
<script>
vegstring = "peas & carrots & parsnips & potatoes & broccoli";
veg=vegstring.split(" & ");
</script>
We would now have a array called veg that looked like veg=["peas","carrots","parsnips","potatoes","broccoli"];.
<script>
veg=["peas","carrots","parsnips","potatoes","broccoli"];
vegstring=veg.join(" & ");
alert(vegstring);
</script>
This would make an alert pop-up with "peas & carrots & parsnips & potatoes & broccoli" inside it.