Languages
[Edit]
EN

TypeScript - get substring before character

0 points
Created by:
Imaan-Morin
1009

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

Quick solution:

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

const index: number = string.indexOf(character);
const substring: string = 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.

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


// usage example:

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

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

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

See also

  1. JavaScript - get substring before character
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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.

❤️💻 🙂

Join