Skip to content

Latest commit

 

History

History
65 lines (61 loc) · 1.78 KB

07_string.md

File metadata and controls

65 lines (61 loc) · 1.78 KB

Usage

We could use single quote or double quote

let s1 = "Let's get started!"; // When String contains single quote('), use double quote("")
let s2 = 'JS is cool.';

Escape special character

let s3 = "Learn JS \"in one day\"."; // use \ to escape
console.log(s3);
// output: Learn JS "in one day".

Template Strings

1. use +

let name = 'Parker';
let habbit = 'coding';
console.log('My name is ' + name + ', I love ' + habbit); 

2. use back-tick(` `)

console.log(`My name is ${name}, I love ${habbit}`);

Useful function & attribute

  • length returns the length of a string
let sayhi = 'Hello JS!'
console.log(sayhi.length);
// output: 9

stringObject.replace(regexp/substr, replacement)

  • replace() returns a new string where the specified values are replaced
let str = 'impossible';
console.log(str.replace('im', "I'm "));
// output: I'm possible

str = 'Willy love dogs. Willy also lvoe cats.';
console.log(str.replace('Willy', 'Parker'));
// output: Parker love dogs. Willy also lvoe cats.
console.log(str.replace(/Willy/g, 'Parker'));
// output: Parker love dogs. Parker also lvoe cats.

g means golbal stating
i means case insensitive

  • toUpperCase() / toLowerCase()
let s = 'I love JS.';
console.log(s.toUpperCase());
// output: I LOVE JS.
console.log(s.toLowerCase());
// output: i love js.
  • split() returns an array of substrings
let fruits = "apple,banana,guava";
console.log(fruits.split(','));
// output: ["apple", "banana", "guava"]

let colors = "red green blue";
console.log(colors.split(' '));
// output: ["red", "green", "blue"]