How to get the substring between two substrings in Node.js

1 Answer

0 votes
function SubstringBetweenTwoSubstrings(str, suba, subb) {
    const posA = str.indexOf(suba);
    const posB = str.lastIndexOf(subb);
 
    if (posA === -1) return "";
 
    if (posB === -1) return "";
 
    const indexEndSuba = posA + suba.length;
    if (indexEndSuba >= posB) return "";
 
    return str.substring(indexEndSuba, posB);
}
 
const str = "Node.js:C#:C C++:Java:Python";
 
console.log(SubstringBetweenTwoSubstrings(str, "C#", "Java"));
 
 
 
 
/*
run:
 
:C C++:
 
*/

 



answered Aug 3, 2024 by avibootz
...