/JS-String-Methods

A reference guide to String Methods in JavaScript



String Methods in JavaScript

Here is a rundown of some useful string methods in JavaScript.
Each method listed below will include the following:

  • A description of what it does
  • Brief explanation of how it works
  • Time complexity (if appropriate)
  • Three code examples
  • Here is a list of all the methods I will cover, in case you want to jump to a particular section!

    List of string Methods

    charAt
    charCodeAt
    concat
    includes
    indexOf
    match
    repeat
    replace
    search
    slice
    split
    substr
    toLowerCase
    toUpperCase
    trim

    charAt

    String.prototype.charAt() takes in an index number, and returns the character at that position. If there is nothing there, it gives back an empty string "".

    Parameters accepted:

    charAt() accepts one parameter:

  • index
  • Basic usage:

    someString.charAt(index)

    Some examples:

    const str = "Hello world"
    str.charAt(2)  
    

    //returns: "l"

    const str = "Hello world"
    str.charAt()  
    
    //returns: "H" because the default is 0
    
    const str = "Hello world"
    str.charAt(99)  
    
    //returns: ""
    

    Back to the list

    charCodeAt

    String.prototype.charCodeAt() takes in an index and returns the Unicode number of the character at that index. This will always be a number between 0 and 65535. If the index is out of the range for the string, .charCodeAt() will return NaN

    Parameters accepted:

    charCodeAt() takes in one parameter:

  • index
  • Basic usage:

    someString.charCodeAt(index)

    Some examples:

    const str = "Hello World"
    str.charCodeAt(2)  
    

    //returns: 108, which is where lowercase l is in the ASCII table

    const str = "Hello World"
    str.charCodeAt()  
    
    //returns: 72
    
    const str = "Hello World"
    str.charCodeAt(99)  
    
    //returns: NaN
    

    Back to the list

    concat

    String.prototype.concat() concatenates (or joins together) the calling string with any strings passed in as arguments. Strings are joined together as-is, so be mindful of spaces!

    Parameters accepted:

  • one or more strings
  • Basic usage:

    someString.concat(string, string, string…)

    Some examples:

    const place = 'World'
    console.log('Hello'.concat(" ", place))
    

    //prints "Hello World"

    ''.concat('Hello', ', ', 'How are you?')  
    
    //returns:  "Hello, How are you?"
    
    
    //using the spread operator to spread an array into .concat()
    const greeting = ["Well ", "hello", " ", "there", "!"]
    console.log("".concat(...greeting))
    
    //prints "Well hello there!"
    

    Back to the list

    includes

    String.prototype.includes() checks if the calling string contains the string that is passed into it. You can pass in an optional position to tell it when to start searching. .includes() returns a boolean (true or false). It is case-sensitive!

    Parameters accepted:

    This method can take two parameters:

  • search string (required)
  • index to start search (the default is 0)
  • Basic usage:

    someString.includes(‘string’, index)

    Some examples:

    const drinks = "We have Coffee, Tea, and Soda"
    drinks.includes("Coffee")
    

    // returns true

    const drinks = "We have Coffee, Tea, and Soda"
    drinks.includes("coffee")
    
    // returns false!!
    
    const sentence = 'How now brown cow?'
    sentence.includes('How', 1)  
    
    // returns false because it started searching at position 1!
    

    Back to the list

    indexOf

    String.prototype.indexOf() is a really handy method that takes in a string (the search value), and returns the index of the first instance of the search value within the calling string. If it isn’t found, .indexOf() will return -1. It’s case sensitive!

    Parameters accepted:

    .indexOf() takes in two parameters:

  • search value (required)
  • position/index to start search (default is 0)
  • Basic usage:

    someString.indexOf(‘searchString’, index)

    Some examples:

    const sentence = "The Antarctic blue whale is the largest animal on Earth."
    sentence.indexOf('blue')  
    

    // returns 14

    const sentence = "It is also the loudest animal on Earth, with a call that can reach 188 decibels."
    sentence.indexOf('earth')  
    
    // returns -1
    
    const sentence = "For context, a jet at take-off is about 150 decibels"
    sentence.indexOf('context', 5)  
    
    // returns -1 because it started searching at position 5!
    

    Back to the list

    match

    String.prototype.match() takes in a Regular Expression, and returns an Array based on what matches the Regular Expression.
    It will return only the first match if the g flag is not used.
    Anything passed into it will be converted into a regular expression object.

    Parameters accepted:

  • a regular expression object
  • Basic usage:

    someString.match(regExp)

    Some examples:

    const sentence = "Cheesy pizza is totally tubular. I love pizza!"
    sentence.match(/PIZZA/i)
    

    //returns ["pizza", index: 7, input: "Cheesy pizza is totally tubular", groups: undefined]

    const sentence = "Cheesy pizza is totally tubular. I love pizza!"
    sentence.match(/PIZZA/gi)
    
    //returns  ["pizza", "pizza"]
    
    const sentence = "One, two, three"
    //searching for a digit
    sentence.match(/\d/gi)
    // returns null    (no match is found)
    
    sentence.match()
    //returns ["", index: 0, input: "One, two, three", groups: undefined]
    

    Back to the list

    repeat

    String.prototype.repeat() copies a string a number of times and concatenates the result. It copies the string it was called upon. It’s pretty straightforward with some examples!

    Parameters accepted:

  • an integer between 0 and `+Infinity`
  • Basic usage:

    someString.repeat(num)

    Some examples:

    'hello!'.repeat(3)
    //returns "hello!hello!hello!"
    
    const sentence = 'Look at the exclamation points'
    console.log(sentence + '!'.repeat(10))
    // prints  "Look at the exclamation points!!!!!!!!!!"
    
    '.'.repeat(Number("3"))
    //returns "..."
    

    Back to the list

    replace

    String.prototype.replace() is pretty powerful. It returns a string that has had parts of it replaced (based on what was passed in). If you pass in a string, it will only replace the first instance of the match!
    You can get it to behave more like String.replaceAll() by using a regular expression with a global flag, g

    Parameters accepted:

    .replace() takes two parameters:

  • a string or a regular expression
  • a replacement string or a callback function
  • Basic usage:

    someString.replace(matchThis, replaceWithThis)

    Some examples:

    const fruits = "Apples, Cookie, Cookie, Kiwis, Bananas, Cookie"
    //replaces only first match:
    fruits.replace("Cookie", "Plum")
    //returns  "Apples, Plum, Cookie, Kiwis, Bananas, Cookie"  
    

    //replaces all, and is case-insensitive! fruits.replace(/cookie/gi, "Mango")
    //returns "Apples, Mango, Mango, Kiwis, Bananas, Mango"

    const ducks = "duck, duck, goose, duck, gopher, goose"  
    ducks.replace(/goose|gopher/g, match => { return (match === 'gopher') ? 'Found-A-Gopher' : 'Found-A-Goose' })  
    
    //returns
    "duck, duck, Found-A-Goose, duck, Found-A-Gopher, Found-A-Goose"
    
    const s = "6 All the11 digits sh8ould be remo0ved 8 fr1om this s7tr0ing"
    const digits = []
    const digitsRemoved = s.replace(/\d/g, match => {
    	digits.push(match)
    	return ""
    })
    
    console.log(digitsRemoved, digits)
    
    //prints
    "All the digits should be removed from this string"
    [ "6", "1", "1", "8", "0", "8", "1", "7", "0" ]
    

    Back to the list

    String.prototype.search() checks a string for a match. It matches using a regular expression. If there’s a match, the index will be returned, otherwise -1 is the return value.

    Parameters accepted:

  • a regular expression object
  • Basic usage:

    someString.search(regexp)

    Some examples:

    const colors = "blue Grey yellow GrEy orange GREY grey pink purple"
    colors.search(/grey/gi)
    

    // returns 5 //notice only one index is returned. .search() returns only the index of the first match

    const expression = new RegExp(/[a-z]/gi) 
    const lettersNums = "82738000c09a78c7s" 
    lettersNums.search(expression)  
    
    // returns 8
    
    const threeNums = new RegExp(/\d{3}/i) 
    const fourNums = new RegExp(/\d{4}/i)
    const str = "23ab fc333 az zza22" 
    
    str.search(threeNums)  
    // returns 7
    
    str.search(fourNums)
    // returns -1
    

    Back to the list

    slice

    String.prototype.slice() returns a “slice” of a string. It commonly takes in two arguments - the index of where to start the slice, and the index after the end of the slice. It doesn’t affect the original string.

    Parameters accepted:

    .slice() can take two parameters:

  • the start index (required)
  • the end index
  • Basic usage:

    someStr.slice(startIndex, endIndex)

    Some examples:

    const pizzaString = "This string has pizza in it!"
    const word = pizzaString.slice(16, 21) 
    console.log(word)  
    

    //prints "pizza"

    //without the 2nd argument
    const str = "Get the second half!"
    const secondHalf = str.slice(str.length/2) 
    console.log(secondHalf)  
    
    //prints  "cond half!"
    
    const str = "Get the last three characters!" 
    const lastThree = str.slice(-3)
    console.log(lastThree)  
    
    //prints  "rs!"
    

    Back to the list

    split

    String.prototype.split() does just that. It “splits” a string apart - however it doesn’t affect the original string. .split() returns an array of substrings.

    Parameters accepted:

    .split() can take two parameters:

  • a separator
  • a limit
  • Note: The limit tells .split() the maximum number of entries that can be in the array of substrings.
    If no separator is passed in, It will return an array containing the string it was called on.

    Basic usage:

    someString.split(separator)

    Some examples:

    const words = "one Two Three"
    console.log(words.split(" ")) //prints [ "one", "Two", "Three" ]
    console.log(words.split())    //prints [ "one Two Three" ]
    
    const phone = "123-456-7890"
    const newPhone = phone.split("-").join(".")
    console.log(newPhone)  
    

    //prints 123.456.7890

    const str = "letters & spaces & things"
    const splitStr = str.split("", 9)
    console.log(splitStr)  
    
    //prints [ "l", "e", "t", "t", "e", "r", "s", " ", "&" ]
    

    Back to the list

    substr

    String.prototype.substr() is a lot like .slice(), in that it returns a substring of the string it is called on. It takes in two values: where to start the substring, and how many characters the substring should be.

    Parameters accepted:

  • startIndex
  • length
  • Note: The length value is capped at the string’s length, so +length or -length. It will count backwards from the end of the string for negative values like we’ve seen before.

    Basic usage:

    someStr.substr(startIndex, number)

    Some examples:

    const str = "hello there"
    const word = str.substr(0, 5)
    console.log(word)  
    

    //prints "hello"

    const str = "hello there"
    const word = str.substr(-5)
    console.log(word)  
    
    //prints "there"
    
    const str = "hello there"
    const words = str.substr(-99)
    console.log(words)  
    
    //prints "hello there"
    

    Back to the list

    toLowerCase

    String.prototype.toLowerCase() returns a lowercase version of the string it’s called on.

    Parameters accepted:

  • none!
  • Basic usage:

    someString.toLowerCase()

    Some examples:

    const yell = "I'm NOT YELLING!"
    const noYell = yell.toLowerCase()
    console.log(noYell)  
    

    //prints "i'm not yelling!"

    'make THIS all Lowercase'.toLowerCase("Ignore this")
    
    //prints "make this all lowercase", even with the unneeded argument
    
    //useful for when you need to avoid case
    const words = ["Banana", "BANANA", "Apple", "Grape", "Banana"]
    
    const noBananas = words.filter(word => word === "banana")
    const bananas = words.filter(word => word.toLowerCase() === "banana") 
    
    console.log(noBananas, bananas)  
    
    //prints
    Array []
    Array(3) [ "Banana", "BANANA", "Banana" ]
    

    Back to the list

    toUpperCase

    String.prototype.toUpperCase(), you guessed it, behaves pretty much like .toLowerCase(), except it makes everything uppercase.

    Parameters accepted:

  • None needed!
  • Basic usage:

    someString.toUpperCase()

    Some examples:

    const string = "abc123def456"
    const upper = string.toUpperCase()
    console.log(upper)  
    

    //prints "ABC123DEF456"

    true.toString().toUpperCase()  
    
    //returns "TRUE"
    
    //useful for searches
    const pasta = ["gnocchi", "Bucatini", "Spaghetti", "linguine", "spaghetti pasta"] const spaghetti = 
    pasta.filter(words => words.toUpperCase().includes("SPAGHETTI")) console.log(spaghetti)  
    
    //prints [ "Spaghetti", "spaghetti pasta" ]
    
    

    Back to the list

    trim

    String.prototype.trim() trims whitespace off of both the beginning and end of a string. That’s all it does! It’s pretty awesome.

    Parameters accepted:

  • none!
  • Basic usage:

    someString.trim()

    Some examples:

    const words = "   Get that whitespace outta here "
    console.log(words.trim())  
    

    //prints "Get that whitespace outta here"

    const words = "  but the space in   between stays   "
    console.log(words.trim())  
    
    //prints "but the space in   between stays"
    
    const spacey = [" Clean ", " up", " the ", " spaces!! "]
    const noSpacey = spacey.map(el => el.trim()) 
    console.log(noSpacey)  
    
    //prints [ "Clean", "up", "the", "spaces!!" ]
    

    Back to the list

    That’s it!

    Thanks for taking the time to check out my little reference manual on string Methods.

    Go forth and use the aforementioned methods to your heart’s content ✨

    The ultimate reference for JavaScript features can be found at the MDN WebDocs