Iām not sure from your original post whether you already know the hexadecimal string fed3ff.. or if thatās what youāre trying to find.
If itās the first case, where you already know the pattern, then this should work:
// save response text
let text = pm.response.text()
// grab your pattern from global variables
let myPattern = pm.globals.get('regEx')
pm.test("body contains regex", function() {
// detect if the pattern exists in the text
pm.expect(text).to.include(`main.${myPattern}.chunk.js`)
})
If youāre trying to FIND the pattern based on whatās in the text, something like this should work:
let text = `... <script type="text/javascript" src="/main.fed3fbbceb96763d430c.chunk.js"></script> ...`
myRe = new RegExp('main\.([^.]*)\.chunk\.js', 'g');
myArray = myRe.exec(text)
pm.test("body contains regex and saves it", function() {
pm.expect(myArray.length).to.be.gte(2)
pm.globals.set('regEx', myArray[1])
})
It was the second option that I was aiming for. I have taken your code and tweaked it to work with a try-catch so that I can run multiple checks for different strings/regex.
(Thereās only 1 at the moment, but the important thing is it works!)
Here is the code for anyone else that encounters the sameā¦
const text = pm.response.text();
myRe = new RegExp('main\.([^.]*)\.chunk\.js', 'g');
myArray = myRe.exec(text);
let count = 0;
pm.test("Check for RegEx", () => {
try {
pm.expect(myArray.length).to.be.gte(2);
pm.test("Body contains regex");
} catch (e) {
pm.test("Body doesn't contain regex", () => {
throw new Error(e.message)
}), count++;
}
if (count > 0) {
console.error("There are failures within the above checks, please check...");
pm.expect.fail("There are " + count + " failures within the above checks, please check...");
}
});
Info about .exec
If the match succeeds, the exec() method returns an array (with extra properties index, input, and if the d flag is set, indices; see below) and updates the lastIndex property of the regular expression object. The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text. If the match fails, the exec() method returns null, and sets lastIndex to 0.
Iāve been playing around with this code and itās working great, but I was wondering if you could clarify what the 'g' part of the code this line does? myRe = new RegExp('main\.([^.]*)\.chunk\.js', 'g');
I have seen examples that use āiā too ā¦ but I canāt seem to find a description of what it does.
With regular expressions you can set flags to run once, or run āgloballyā (aka, find multiple matches). I tend to use āglobalā with most of what I do with regex, so itās just kind of a default for me
Youāre welcome to remove the āgā and that will only find the first match.