EN
JavaScript - get substring before character
3
points
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