2

Please note that I don't know what the full class I'm wanting to isolate is, only its format, which is for example:

class="loadable context-enc encounterTimelineEncounterDateitem"

What I'm looking for is context-enc or something that matches:

.match(/\bcontext-[a-z]+\b/)

and it's really the [a-z]+ part that I want to discover. I don't want to so much test whether there IS a class in there that matches, but want to know what the string after "context-" is (in this case 'enc'). Something like:

function getcontext(class, 'context-'){ .. }

2 Answers 2

2

You can wrap the [a-z+] in your regex in parentheses to get the value back in a capture group:

"context-enc".match(/\bcontext-([a-z]+)\b/)

["context-enc", "enc"]

Sign up to request clarification or add additional context in comments.

1 Comment

THANKS! I was torn between voting yours or @Ben_Thielker as the accepted answer - you both answered a part of the question, and now I know how to approach back-references in JS (which I already knew in PHP's preg_match() using the 3rd parameter.
0

The following function would likely return what you want...

function getContext(className, withString){
    var r = new RegExp("\\b"+ withString +"[a-z]+\\b");
    var s = new RegExp("^"+withString);
    return className.match(r)[0].replace(s,'');
}

If you build the regular expression dynamically you can insert your variable content into it, and then to isolate the [a-z]+ portion just remove the searched for string from the result.

EDIT: Using @nathan-taylor's capture group suggestion we can simplify the function to:

function getContext(className, withString){
    var r = new RegExp("\\b"+ withString +"([a-z]+)\\b");
    return className.match(r)[1];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.