user1322801 user1322801 - 1 month ago 10
Javascript Question

Looking for JS Regex that finds data between . and , or '

I have strings of the following type:

ns1.importantClassA,ns1.nonImportantClass
ns2.importantClassB'1[ns2.nonImportantClass1,ns2.nonImportantClass2]


I need to retrieve the names of the important Classes (importantClassA, importantClassB).

I have created the following code for the moment:

function getData(fullPath)
{
var retVal = fullPath;
var endIndex = retVal.indexOf(",");
var endIndexOption2 = retVal.indexOf("`");
if (endIndexOption2 != -1 && endIndexOption2<endIndex)
{
endIndex = endIndexOption2;
}

if (endIndex != -1)
{
var startIndex = retVal.lastIndexOf('.',endIndex);
if (startIndex != -1)
{
retVal = retVal.substr(startIndex+1,endIndex-startIndex-1);
}
}
return retVal;
}


but obviously a regex will simplify it.
Any suggestions?

Answer

I'm not very good at regex, but this may be the one you're looking for:

/^.*?\.(.*?)(?:,|').*/

test:

    var sample1 = "ns1.importantClassA,ns1.nonImportantClass"
    var sample2 = "ns2.importantClassB'1[ns2.nonImportantClass1,ns2.nonImportantClass2]"
    var regex = /^.*?\.(.*?)(?:,|').*/

    document.write(sample1.replace(regex, "$1") + "<br>");
    document.write(sample2.replace(regex, "$1") + "<br>");