# Strings
# Properties & Methods (opens new window)
# .length (opens new window)
property - contains the length of the string, in UTF-16 code units
- to get the last letter of a string, you can subtract one from the string's length.
var lastLetter = firstName[firstName.length - 1];
# square bracket notation []
return any character inside a string
- But string values are immutable:
str[0]="x"doesn't work
# indexOf() (opens new window)
checks if a substring is present inside a string
- If the substring is found inside the main string, it returns a number representing the index position of the substring
- If the substring is not found inside the main string, it returns a value of -1.
if(browserType.indexOf('mozilla') === -1) {
// do stuff with the string if the 'mozilla'
// substring is NOT contained within it
}
# .lastIndexOf() (opens new window)
# slice() (opens new window)
extracts a section of a string and returns it as a new string, without modifying the original string.
- the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted.
- to extract all of the remaining characters in a string after a certain character, don't include the second parameter!
slice(x,y)slice (start-end)slice(-4)last 4 letters
# toLowerCase() (opens new window) - toUpperCase() (opens new window)
convert all the characters to lower- or uppercase
# replace() (opens new window)
replace one substring inside a string with another substring.
- two parameters — the string you want to replace, and the string you want to replace it with.
- doesn't change the string
# .split() (opens new window)
divides a String into an array
let digits = number.toString().split('');converts number into an array of strings for each digit
# .repeat() (opens new window)
returns a new string which contains the specified number of copies of the string on which it was called
# .trim() (opens new window)
# .trimStart() (opens new window) - .trimEnd() (opens new window)
# .substring() (opens new window)
# .substr() (opens new window)
# .replaceAll() (opens new window)
# .endsWith() (opens new window)
# .concat() (opens new window)
# .includes() (opens new window)
# Number to String
let str = `${number}`
let str = number + ""
let str = String(number)
# String Concatenation
let name = 'John'
let age = '32'
console.log ("Hello, my name is " + name + " and I am " + age + " years old")
let firstName = 'John';
let lastName = 'Doe'
let fullName = firstName + ' ' + lastName
console.log (fullName);
# Template Literals
template literals use backticks ` and ${} to interpolate values into a string
in template literals ${..}is called codeblock
const myPet = 'cat';
console.log(`I have a ${myPet}.`);
// Output: I have a cat.
# Strings - Escape Character \
\n- Newline\'- Single quote\"- Double quote\\- Backslash\t- Horizontal Tab\v- Vertical Tab\0- Nul char