Strings are the second most common data type used in JavaScript, and in many cases, since JavaScript is so widely used for web applications, it is the prominent data type. In this article I’ll discuss how strings work in JavaScript and how to work with them efficiently and effectively. I’ll also discuss some newer abilities of strings that are just being discovered and used.

Strings Defined

A string is any set of 0 or more characters enclosed in either single quotes or double quotes. The characters in a string can be alphabetic characters, numbers, symbols, and spaces. Here are some examples of JavaScript string literals:

"hello world"
'good bye, world!'
"1600 Pennsylvania Avenue"
'$*&!@ it!'

If you are using single quotes in your string, and you need to embed a single quote to write out a contraction, you use the backslash character (\) as an escape character. To see why you need to do this, let’s look at what happens when you don’t escape a single quote by writing out such a string in the JavaScript shell:

js> 'can't'
typein:1:5 SyntaxError: unexpected token: identifier:
typein:1:5 'can't'
typein:1:5 .....^

The interpreter can’t figure out what to do with the ‘t’ after the single quote.

Now watch what happens when we escape the single quote:

js> 'can\'t'
"can't"

The escape character tells the interpreter to treat the single quote as an apostrophe and not as an “end-of-string” character.

You can embed other characters into a string, including the newline character (\n) and the tab character (\t). Here are some examples using the shell:

js> print("Hello, \n world!");
Hello,
world!
js> print("Hello, \tworld");
Hello,  world

#javascript-training #learn-to-code #learn-to-program #javascript #javascript-tutorial #deep learning

Learning JavaScript: Working with Strings
2.60 GEEK