JavaScript - String Methods Flashcards
replace()
Returns: new string
The original string is left unchanged.
some or all matches of a pattern replaced by a replacement.
The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
If pattern is a string, only the first occurrence will be replaced.
slice()
Returns: a new string
The original string is left unchanged.
extracts a section of a string and returns it as a new string, without modifying the original string.
split()
Returns: an array of strings
Changes the original string in place
divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method’s call.
E.g. const str = ‘The quick brown fox jumps over the lazy dog.’;
const words = str.split(' '); console.log(words[3]); // expected output: "fox"
const chars = str.split(''); console.log(chars[8]); // expected output: "k"
const strCopy = str.split(); console.log(strCopy); // expected output: Array ["The quick brown fox jumps over the lazy dog."]
charAt()
Returns: new string
returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.
concat()
Returns: A new string containing the combined text of the strings provided.
method concatenates the string arguments to the calling string and returns a new string.
const str1 = 'Hello'; const str2 = 'World';
console.log(str1.concat(' ', str2)); // expected output: "Hello World"
console.log(str2.concat(', ', str1)); // expected output: "World, Hello"
includes()
Returns: true if the search string is found anywhere within the given string; otherwise, false if not.
includes() method determines whether one string may be found within another string, returning true or false as appropriate.
endsWith()
Returns: returning true or false as appropriate.
method determines whether a string ends with the characters of a specified string
match()
Returns: An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.
method retrieves the result of matching a string against a regular expression.