js substring between two characters


// This function will return the substring between two characters
function getSubString(str, startChar, endChar){
    // Get the index of the start character
    let startIndex = str.indexOf(startChar);

    // Get the index of the end character
    let endIndex = str.indexOf(endChar);

    // Check if both the start and end character exist in the string
    if(startIndex !== -1 && endIndex !== -1){
        // Return the substring between the start and end character
        return str.substring(startIndex + 1, endIndex);
    } else {
        // If the start and end character does not exist, return null
        return null;
    }
}

// Get the substring between '[' and ']'
let subString = getSubString("This is a [sample] string", "[", "]");

// Output: 'sample'
console.log(subString);
    

This function can be used to get the substring of a string that is between two characters. For example, if we have a string such as "This is a [sample] string", we can use this function to get the substring between the "[" and "]" characters, which will be "sample". The function takes in a string, the start character, and the end character as parameters. First, it uses the JavaScript indexOf() function to get the index of the start and end characters. If both the start and end character exist, then it uses the substring() function to return the substring between the start and end character. If either the start or end character does not exist, then it returns null. In the example above, the start character is "[" and the end character is "]", so the resulting substring will be "sample".

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe