Skip to content
the poor coder

js substring between two characters

Poor Man
Published
Reading time
1 min read
JavaScript

// 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".

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC