Droplets of water suspended on strings

In JavaScript, a string is any text between single or double quotes, including letters, numbers, and Unicode characters:

"This is a string"
'This is also a string'
"Forever 21, too, is a string"

Single quotes can be included in a string if the string itself is surrounded by double quotes, and vice-versa.

'This is "okay"'

Otherwise, quotes and other special characters inside a string should be escaped with a leading backwards slash character:

Escape StringRepresents
\'single quote
\"double quote
\nnew line
\rcarriage return

For example:

"This is \t Tab-delimited \t Text"

Indexing Strings

Like arrays, the first character in a string is considered to be at position 0, the second one at position 1, and so on. Note that the length of a string includes every character in it, including spaces but excluding escape characters:

var nicchia = "Virginia Elisabetta Luisa Carlotta Antonietta Teresa Maria Oldoini";
> 66

There are many functions and methods associated with strings, all of which I will cover in future articles.

Numbers as Strings

Sometimes you’ll receive a number that JavaScript doesn’t appear to treat as one. A good example is an HTML5 form number input:

<label for="weight">Enter the weight of the package in kilos</label>
<input type="number" id="weight" min="1" max="10" value="0">

If we try to read the value using traditional JavaScript and add 1 to it:

weight.addEventListener("input", function() {
console.log(weight.value + 1);

… the result we get in the console when "1" is entered into the number field is not "2", but "11". This reflects the problem of concatenation: value treats the entry in the number field as a string, not a number. There are two ways of dealing with this:

  1. Use the correct method: weight.valueAsNumber, rather than weight.value, This will report the entry in the field as an actual number.
  2. Stick with the value method but convert the text entered into a true number using parseInt:
weight = document.getElementById("weight");
weight.addEventListener("input", function() {
console.log(parseInt(weight.value, 10) + 1);

I’ll have more to say about parseInt in a future article.

Converting Numbers Into Strings

Sometimes you’ll want to do the reverse: convert a number into a string. If I have a variable named wonders:

var wonders = 7;

…I can convert it into a string by using .toString():

var wonderString = wonders.toString();

…or by adding an empty quote to it:

var wonderString = wonders + "";

Either works, although you may find the second method faster in loops (over millions of operations).

Photograph by Rob Franksdad, licensed under Attribution-NonCommercial-ShareAlike 2.0 Generic license.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.