Get the Part After a Character in a String in JavaScript or Node.js

JavaScript comes with handy string methods. It provides useful basics to interact with strings. The standard library has some missing pieces which you can fill yourself by composing helpful utility methods.

One of these utilities is a function retrieve the part after a given character in a JavaScript string. This tutorial shows you how to approach it!

Node.js Series Overview

Retrieve the Part After a Character in a String

Let’s create a strAfter helper function returning the part of a string after a given delimiter.

A way to approach this is to split a given string at each occurrence of the delimiter. This results in an array containing all the matches. From here, remove the first match and rejoin the remaining matches with the delimiter to return everything of the string after the first occurrence of the delimiter:

function strAfter (string, delimiter) {  
  if (delimiter === '') {
    return string
  }

  const substrings = string.split(delimiter)

  return substrings.length === 1
    ? string // delimiter is not part of the string
    : substrings.slice(1).join(delimiter)
}


// Using strAfter

const range = 'A1:L200'  
const end = strAfter(range, ':')  
// L200


const slug = '2020-this-is-a-tutorial-slug')  
const scrambledSlug = strAfter(slug, '-')  
// 'this-is-a-tutorial-slug'

The check if the given delimiter is empty is important. JavaScript splits a given string value at each character when using an empty string as the delimiter. Ensure you’re actually splitting a string at a valid delimiter.

The implementation of strAfter returns the full, original string in case the delimiter is not found. If you want another behavior in this situation, you should adjust the implementation :)

Use a Package

I’m the maintainer of the @supercharge/strings package providing convenient string utilities.

The package provides a fluent interface to interact with strings. One of the available methods is .after(delimiter) returning the part of the string after the first occurrence of the given delimiter:

const Str = require('@supercharge/strings')

Str('A1:L200').after(':').get()  
// 'L200'

Str('2020-this-is-a-tutorial-slug').after('-').get()  
// 'this-is-a-tutorial-slug'

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.