Jump to content
WAPT Forum
Sign in to follow this  
Guest taliesin

Regular expression random match

Recommended Posts

Guest taliesin

This took me quite a while to figure out. Sometimes the Search funtion is just not good enough and you need the power of regular expressions.

 

Javascript code to be saved in a file and referenced.

function RegularExpressionRandomMatch(regularExpression, positionMatch, flags)
{
    positionMatch = positionMatch || "0";
    flags = flags || "g";
    
    var stringToMatchAgainst = context.document.documentElement.innerHTML;
    var regex = new RegExp(regularExpression, flags);
    
    var matches = [];
    while ((match = regex.exec(stringToMatchAgainst)) != null)
    {
        matches.push(match)
    }
    
    var numberOfMatches = matches.length;
    if (numberOfMatches < 1) return "";
    var randomNumber = Math.floor(Math.random() * numberOfMatches);
    var randomMatch = matches[randomNumber][positionMatch];
    return randomMatch;
}

 

Example usage (add a javascript function)

 

Function Name:

RegularExpressionRandomMatch

 

Function Parameters:

updateBasket\('(\d+)','0','0'\)

1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...