DEV Community

loading...

Notes: Strings, Backlashes, Quotes etc.

rthefounding profile image Randy Rivera ・2 min read

During this part of the section or at least my blog, I'll be learning and showing you about strings.

var myFirstName = "Randy";
var myLastName = "Rivera";
Enter fullscreen mode Exit fullscreen mode

I created two variables myFirstName and myLastName and assigned them values.
"Randy" is called a string literal. It's a string because it is a series of zero or more characters enclosed in single or double quotes.

Escaping literal quotes in strings.

When you're creating a string you must start and end with a single or double quote. Although what if you need a literal quote: " or ' inside of your string?.
You can definitely use them by placing a backslash () in front of the quote.

var someStr = "My cousin said, \"Randy wants to become a programmer\".";
Enter fullscreen mode Exit fullscreen mode

When you print this to the console you will get:

My cousin said, "Randy wants to become a programmer".
Enter fullscreen mode Exit fullscreen mode
Code    Output
\'   single quote
\"   double quote
\\   backslash
\n   newline
\r   carriage return
\t   tab
\b   word boundary
\f   form feed
Enter fullscreen mode Exit fullscreen mode
  • Helpful chart.

Concatenating Strings with Plus Operator

In JavaScript, when the + operator is used with a String value, it is called the concatenation operator. You can build a new string out of other strings by bringing them together.
Example:

var myStr = "I'm First. " + "I'm Second."
Enter fullscreen mode Exit fullscreen mode

Note: Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
The console would display the string I'm First. I'm Second.

Constructing Strings with Variables

Sometimes you will need to build a string, Mad Libs style. By using the concatenation operator (+), you can insert one or more variables into a string you're building.
Example:

var myName = "Randy";
var someStr = "Hello, my name is " + ourName + ", how are you?";
Enter fullscreen mode Exit fullscreen mode

someStr would have a value of the string Hello my name is Randy, how are you?.

Finding the Length of a string

You can find the length of a String value by writing .length after the string variable or string literal.
For example:
we create a variable

var firstNameLength = 0;
var firstName = "Randy";
Enter fullscreen mode Exit fullscreen mode

we could find out how long the string Randy is by using the firstName.length property. Let's count the number of characters in the FirstName variable and assign it to firstNameLength.

firstNameLength = firstName.length;
console.log(firstName.length) // 5
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide