JavaScript - get substring before character

3 points
Created by:

In this article, we would like to show you how to get substring before character using JavaScript.

Quick solution:

const character = ':';
const string = 'user:password';

const index = string.indexOf(character);
const substring = string.substring(0, index);

console.log(substring);  // user


Practical example

In this example, we create a reusable function that helps to get the substring before indicated character.

// ONLINE-RUNNER:browser;

const getSubstring = (string, character) => {
    const index = string.indexOf(character);
    return string.substring(0, index);

// usage example:

const text1 = 'value1: some text...';
const text2 = 'value2: some text...';

const result1 = getSubstring(text1, ':');  // value1
const result2 = getSubstring(text2, ':');  // value2

console.log(result1);  // value1
console.log(result2);  // value2

See also

  1. JavaScript - get substring after character 
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂