String Methods Flashcards
Length
Find the length of a string
var.length
.trim()
Removing white space
Used when processing the string of a user input field
.includes()
Determines if string contains substring
returns true or false
Used for string matching or searching/parsing
.indexOf()
Finding the index of a substring
returns the index of the substring within the string
if no substring, returns -1
Used to check if index is greater than -1 (aka does the substring exist within the string?) using a conditional
.toUpperCase()
returns a string with all uppercase letters
.toLowerCase()
returns string in lower case letters
.replace()
Replaces strings with new values
returns a string with a pattern replaced by a replacement string
using regex- can globally replace
using string - can only replace the first occurence
ex: const str = ‘hello world! my name is also world.”
const stringPattern = ‘world’
const regexPattern = /world/gi
const replacement = ‘gitconnected’
console.log(str.replace(stringPattern, replacement)) //Hello gitconnected! my name is also world
console.log(str.replace(regexPattern, replacement)) //Hello gitconnected! my name is also gitconnected.
.slice()
- returns a section of a string
- extracts a section of a string based on the index (first param is the first index, second is optional ending)
- negative begin index: slice backwards from the end
- can use with indexOf() as a reference point
.split()
- converts into an array
- This is useful when you know your string uses a certain character to separate data, or if you want to operate on specific substrings individually.
.repeat()
Repeats a string a specified number of times
pass number of times as the param
.match()
Returns array of matching strings (returns the ones that match) when comparing a string against a regular expression
.charAt()
Returns a character at an index
param is the index num
.charCodeAt()
Returns the unicode of the char at a specified index
(UTF-16 cone integer between 0 and 65535.)