Articles HTML Tutorial CSS Tutorial JavaScript Tutorial PHP Tutorial MYSQL Tutorial Contact Us
JAVASCRIPT Strings

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>
text1 = "Hi, my name is Simon.";
text2 = "I'm very please to meet you!";
combined = text1+" "+text2;
alert(combined);
</script>
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.";
alert(text.length);
</script>
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(" & ");
</script>
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>
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.