[JavaScript] String

Cadet_42·2021년 7월 27일
0

JavaScript

목록 보기
4/8
post-thumbnail

Introduction

A string in any programming language is simply a sequence of characters between quotes. A character can be a letter, number, punctuation, or even new lines and tabs. It just needs to be between quotes.

You can use any of the following types of quotes when creating a string:

  • "" - double quotes,
  • '' - single quotes and
  • `` - backticks (in most keyboards, it is placed above the tab on the left corner).

Using the backticks will be useful if you want to:

  • interpolate variables into the strings or
  • have a multiline string.

String interpolation is a common practice that allows you to add the value of a variable directly inside a string. It is only available when using backticks and is achieved by wrapping a variable inside ${} and adding it to the string, check the code below and it will make more sense!

Example 1)

Input:

let language = 'JavaScript';
console.log(`I am learning ${language}!`);

Output:

"I am learning JavaScript!"

Example 2)

Input :

const voyage = `
- Italy for a coffee
- UK for a shopping & musicals
- Spain for a churros 
- Vienna for a coffee also!`

console.log(`I REALLY want to go for a voyage... ${voyage}`);

Output :

"I REALLY want to go for a voyage... 
- Italy for a coffee
- UK for a shopping & musicals
- Spain for a churros 
- Vienna for a coffee also!"

String tips & tricks

Concatenation

❗️ You can easily concatenate or add characters to strings with the + or += operator.

let emptyCon = "heyyy ";
emptyCon += "G'day mate!";

console.log(emptyCon);

"heyyy G'day mate!"

❗️ In JavaScript, you can concatenate numbers with strings:

Result Skip Results Iframe
EDIT ON
let age = 21;
console.log(`I am ${age} years old`);
console.log("How old are you? Seriously ...");
console.log(`I am ${age+12} years old.`);

The .length property

❗️ To use the .length property, need to use the backticks(``)!

const fact = `I love Takroux!`;
console.log(`"${fact} is a string and the length is ${fact.length}"`)
"'I love Takroux! is a string and the length is 15'"

The .toUpperCase() method

.toUppercase() is a method of string data types in JS that allows you to change all the letters in a string to their Uppercase version

Apply .toUpperCase() code :

let name = "Yooyoo";
let up = name.toUpperCase();
console.log(up);

output :
YOOYOO

Doesn't work in this way

let catName = "Tak roux";
console.log(.toUpperCase(catName));

As you can see, to use .toUpperCase() and any other methods in JS we always need to use () at the end. However, when we use .length and other attributes, we do not use the parentheses.

Accessing a single character of a string using its index

You can access characters inside of strings with their index number.
The index determines the character order in the word, from left to right, but be aware the index always starts at 0. To access a character via its index you can use [] like shown in the example below.

const greeting = "Hello";
console.log(greeting[0]); // => H
console.log(greeting[4]); // => o
console.log(greeting[9]); // => undefined
console.log(greeting[-2]); // => undefined

Accessing a substring

- .indexOf(substring)

JavaScript has a cool indexOf() method that returns the index of a particular character/string occurrence. If the substring was not found, it returns -1. To use it you just need to put the character or characters string you want to know the index of inside the () of indexOf() as shown below.

const favoritePhrase = "Don't be evil";

console.log(favoritePhrase.indexOf("Don't")); // => 0

console.log(favoritePhrase.indexOf("e")); // => 7 because indexOf prints the FIRST occurance

console.log(favoritePhrase.indexOf("z")); // -1 since it's not found

❗️ If a word has the same character/substring two or more times, the indexOf() method will return the index of the first occurrence.

- .slice(start, end)

  • the slice() method extracts a part of a string and returns it as a new string, without modifying the original string.

let statement = "I am the Ironhacker and I can't wait for this course to start!!!";

// it is zero indexed ==> starts with zero
let test1 = statement.slice(0, 19);
console.log(test1); // => I am the Ironhacker

// if the second parameter is not passed, it will capture 
// from the character found on the position that corelates with passed number 
// to the end of the string
let test2 = statement.slice(24);
console.log(test2); // => I can't wait for this course to start!!!

// if negative nuber is passed, the count starts from the end of the string
let test3 = statement.slice(-8);
console.log(test3); // => start!!!

Based on what we've learned...Exercise!

let turtle1 = 'Leonardo';
let turtle2 = 'Raphael';
let turtle3 = 'Donatello';
let turtle4 = 'Michelangelo';

let allTurtles = ' ';
allTurtles += turtle1;
allTurtles += ' ' + turtle2;
allTurtles += ' ' + turtle3;
allTurtles += ' ' + turtle4;
console.log(allTurtles);
console.log(allTurtles.indexOf('Donatello'));
console.log(allTurtles.length);

const like = `
- Coffee
- Tak Roux
- peace
`
console.log(`My favorites are: ${like}` + allTurtles);

Output

18
40
"My favorites are: 
- Coffee
- Tak Roux
- peace
 Leonardo Raphael Donatello Michelangelo"
profile
안녕하세요! 개발공부를 하고 있습니다. 감사히 배우겠습니다. ;)

0개의 댓글