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

JavaScript comes with handy string methods. It provides the basics which allow you to compose the desired functionality. Even though the exact function is not part of JavaScript itself, the available methods allow you to create helper functions providing what you need.

This tutorial shows you how to retrieve the part before a given character in a JavaScript string.

Node.js Series Overview

Retrieve the Part Before a Character in a String

Let’s create a helper function strBefore(string, delimiter) that returns everything from the given string value coming before the delimiter.

A way to implement this handling is to split the given string value at all occurrences of the delimiter and then return the first match.

Here’s how you can implement the strBefore helper method.

function strBefore (string, delimiter) {  
  return delimiter === ''
    ? string
    : string.split(delimiter).shift()

// Using strBefore

const range = 'A1:L200'  
const start = strBefore(range, ':')  
// A1

const slug = '2020-this-is-a-tutorial-slug'  
const year = strBefore(slug, '-')  
// '2020'

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 the delimiter by checking whether the given value is empty.

At this point, the implementation of strBefore returns the original string if 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 .before(delimiter) returning the part of the string before the first occurrence of the given delimiter:

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

// 'A1'

// '2020'


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.