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

JavaScript’s stdlib for strings contains a solid foundation. It provides a lot of useful methods. It can’t provide methods for every use case. Yet, you can surely build your own utility methods using the existing functionality.

This tutorial shows you how to retrieve the part of a string before the first occurrence of a given delimiter.

Node.js Series Overview

Retrieve the String Before a Delimiter

You may want to retrieve the part of a string before the first occurrence of a given character or character sequence. JavaScript comes with the split method allowing you to split a string at a given delimiter.

The split method returns an array of ordered strings, split at the given character(s). You want the first item of that array of splits. That means the part before the delimiter is the first item in the split array.

Here’s a before utility function returning the part before a given delimiter:

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

  return delimiter === ''
    ? value
    : value.split(delimiter).shift()
}

Then you can use the before function like this:

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

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

before('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#before method returning the part of a string before the given character(s):

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

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

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

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

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.