Single and Double Quotes in JavaScript Strings
Strings in JavaScript are contained within a pair of either single quotation marks '' or double quotation marks "". Both quotes represent Strings but be sure to choose one and STICK WITH IT. If you start with a single quote, you need to end with a single quote. There are pros and cons to using both IE single quotes tend to make it easier to write HTML within Javascript as you don’t have to escape the line with a double quote.
console.log('This is a string. 👏')
// output: This is a string. 👏
console.log("This is the 2nd string. 💁");
// output: This is the 2nd string. 💁
Enclosing Quotation Marks
Let’s say you’re trying to use quotation marks inside a string. You’ll need to use opposite quotation marks inside and outside of JavaScript single or double quotes. That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes.
console.log("It's six o'clock.");
// output: It's six o'clock.
console.log('Remember to say "please" and "thank you."');
// output: Remember to say "please" and "thank you.
Alternatively, you can use a backslash \ to escape the quotation marks. This lets JavaScript know in advance that you want to use a special character.
Here’s what that looks like reusing the examples above:
console.log('It\'s six o\'clock.');
// output: It's six o'clock.
console.log("Remember to say \"please\" and \"thank you.\"");
// output: Remember to say "please" and "thank you".
String Methods and Properties
Strings have their own built-in variables and functions, also known as properties and methods. Here are some of the most common ones.
String Length
A string’s length property keeps track of how many characters it has.
// EXAMPLE
console.log("caterpillar".length);
// output: 11
toLowerCase Method
A string’s toLowerCase method in JavaScript returns a copy of the string with its letters converted to lowercase. Numbers, symbols, and other characters are not affected.
console.log("THE KIDS".toLowerCase());
// Example
// output: the kids
toUpperCase Method
A string’s toUpperCase method returns a copy of the string with its letters converted to capitals. Numbers, symbols, and other characters are not affected.
// EXAMPLE
console.log("I wish I were big.".toUpperCase());
// output: I WISH I WERE BIG.
trim Method
A string’s trim method returns a copy of the string with beginning and ending whitespace characters removed.
// EXAMPLE
console.log(" but keep the middle spaces ".trim());
// output but keep the middle spaces
Top comments (0)