EN
JavaScript - get substring after character
3 points
In this article, we would like to show you how to get substring after character using JavaScript.
Quick solution:
xxxxxxxxxx
1
const character = ':';
2
const string = 'user:password';
3
4
const index = string.indexOf(character);
5
const substring = string.substring(index + 1);
6
7
console.log(substring); // password
In this example, we create a reusable function that helps to get the substring after indicated character.
xxxxxxxxxx
1
const getSubstring = (string, character) => {
2
const index = string.indexOf(character);
3
return string.substring(index + 1);
4
};
5
6
7
// usage example:
8
9
const text1 = 'Get the value:value1';
10
const text2 = 'Get the value:value2';
11
12
const result1 = getSubstring(text1, ':'); // value1
13
const result2 = getSubstring(text2, ':'); // value2
14
15
console.log(result1); // value1
16
console.log(result2); // value2