s

javascript get string between two strings edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 18 January 2021 | 3637

Here is the sample code to get the string between two strings using javascript. I have extended the String prototype so that its very simple to find the sub string like the sample code below

Solution

String.prototype.substringBetween = function (string1, string2) {
        if ((this.indexOf(string1, 0) == -1) || (this.indexOf(string2, this.indexOf(string1, 0)) == -1)) {
            return (-1);
        } else {
            return this.substring((this.indexOf(string1, 0)   string1.length), (this.indexOf(string2, this.indexOf(string1, 0))));
        }
};

You can find the string between two strings like the code below. Since I have extended the string using prototype you can use string.substringBetween to find the string between two strings.

alert("Hello World JQuery String Between Two String".substringBetween("Hello World", "Between"));


To give you a snapshot of the output. I opened the developer tools and pasted the function and called the code above. Below is the screenshot of output that displays string between two strings using javascript.