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

JavaScript’s stdlib for strings contains dozens of methods. These methods are useful in a lot of situations. Yet, there are use cases where a method doesn’t exist in the stdlib.

For example, there’s no method to retrieve a part of a string after a character or character sequence. For this case, you need to build your own utility method using the existing functionality.

That’s what this tutorial shows you: how to retrieve the part of a string after the first occurrence of a given delimiter.

Node.js Series Overview

Retrieve the String After a Delimiter

When interacting with string values you may want to retrieve a portion of the string after a given character sequence. This “after” method isn’t available in JavaScript directly and we’re building it ourselves.

JavaScript comes with the String#split method allowing you to split a string at a given delimiter. The split method returns an ordered array of substrings.

The after utility method should return the remainder of a string after matching the occurrence of a character sequence. That means you want to return everything from the array of substrings except the first item.

In case the divided array of substrings contains only one item, it means the delimiter value wasn’t found and you’re returning the original string value.

Here’s a sample after utility function returning the remainder of a string after the first occurrence of a given character:

/**
 * Returns the portion of the string after the first occurrence of the given `delimiter`.
 *
 * @param {String} value
 * @param {String} delimiter
 *
 * @returns {String}
 */
function after (value, delimiter) {  
  value = value || ''

  if (value === '') {
    return value
  }

  const substrings = this.split(delimiter)

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

Then you can use the after function like this:

after('Future Studio is an awesome island', 'is')  
// ' an awesome island'

after('Future Studio is an awesome island', 'great')  
// 'Future Studio is an awesome island'

after('Future Studio')  
// 'Future Studio'

Use the @supercharge/strings Package

I’m the maintainer of the @supercharge/strings package providing convenient string utilities. It provides a useful Str#after method returning the remainder of the string after the first occurrence of a given character or character sequence:

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

Str('Future Studio is an awesome island').after('is')  
// ' an awesome island'

Str('Future Studio is an awesome island').after('great')  
// 'Future Studio is an awesome island'

Str('Future Studio').after()  
// 'Future Studio'

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.