In this tutorial you will learn how to get Substring between two characters using javascript;
In Javascript to get a substring between two characters you need to get the index after the first occurrence of the character. then need to get the index of the last occurrence of the character. After that use the String.slice() method to get a substring between the 2 characters.
Example 1:
To get the start index, we locate the first occurrence of the character and add 1 because the start index parameter is inclusive.
const str = 'one:two;three';
const middle = str.slice(
str.indexOf(':') + 1,
str.lastIndexOf(';'),
);
console.log(middle); // two
Example 2:
This example would also work if we had different separators.
const str = 'one!two?three';
const middle = str.slice(
str.indexOf('!') + 1,
str.lastIndexOf('?'),
);
console.log(middle); // two
Example 3:
Here we can get the middle character using the hyphen ;
const str = 'start-middle-end';
const middle = str.slice(
str.indexOf('-') + 1,
str.lastIndexOf('-'),
);
console.log(middle); // middle
Hope these examples help you to get the middle character in javascript