The Spanner logo
    • Home
    • Blog
      • Blog home
      • RSS
    • Login
    • Home
    • Blog
      • Blog home
      • RSS
    • Login
    The Spanner logo

    The Spanner
    Web security blog

    Made by Gareth Heyes
    Follow me on Twitter: @garethheyes

    Javascript for hackers!

    Hackvertor logo
    Shazzer logo
    My Github account
    Recent posts
    Introducing Feedworm: A Privacy-First RSS Reader That Lives in DevToolsSpeedy RSVP extensionAutoVaderHackvertor history and tag finderShadow Repeater v1.2.3 releaseBurp Hackvertor v2.1.24 releaseHacking roomsXSSing TypeErrors in SafarivalueOf: Another way to get thisMaking the Unexploitable Exploitable with X-Mixed-Replace on FirefoxThe curious case of the evt parameterCSS-Only Tic Tac Toe ChallengeRewriting relative urls with the base tag in SafariBypassing DOMPurify with mXSSNew IE mutation vectorHow I smashed MentalJSMentalJS DOM bypassAnother XSS auditor bypassXSS Auditor bypassBypassing the IE XSS filterUnbreakable filterMentalJS bypassesmXSSJava SerializationBypassing the XSS filter using function reassignmentRPOSandboxed jQueryX-Domain scroll detection on IE using focusEpic fail IEnew operatorDecoding complex non-alphanumeric JavaScriptHacking FirefoxDOM ClobberingBypassing XSS AuditorThe evolution of codeNon-Alpha PHP in 6-7 charsetTweetable PHP-Non AlphaMentalJS for PHPOpera x domain with video tutorialSandboxing and parsing jQuery in 100ms

    Javascript regular expressions

    By Gareth Heyes (@hackvertor)

    Published 18 years 3 months ago • Last updated March 22, 2025 • ⏱️ 2 min read

    ← Back to articles

    Ronald and I had a good conversation about Javascript regular expressions comparing them to PHP. He was having difficultly with the syntax because he was used to preg in PHP so I promised to share my knowledge gained from developing various online scripts.

    First up preg_match in PHP can be achieved using the match function in Javascript, they are both very similar but it's just a matter of getting your head round the different syntax. Match is part of the String object and here is how to use it:-

    <pre lang="javascript"> alert('Test'.match(/[a-z]/)) </pre>

    You can match subpatterns like this (I've tried to keep it close to PHP syntax as possible):-

    <pre lang="javascript"> pattern = /([a-z]+)([0-9]+)([A-Z]+)/; subject = 'test1234TEST'; matches = subject.match(pattern); match1 = matches[1]; match2 = matches[2]; match3 = matches[3]; alert(match1); alert(match2); alert(match3); </pre>

    You can also create matches using the RegExp object, this is useful for passing variables into the pattern which to my knowledge isn't possible with "//" syntax.

    <pre lang="javascript"> a = 'a+'; alert(new RegExp(a).exec('123aaaabcdef')); </pre>

    The exec method can also be called from "//" patterns.

    <pre lang="javascript"> alert((/[0-9]+/).exec('12345abcdef')) </pre>

    Javascript supports the modifiers "g", "i" and "m", here's how to use them with "//" syntax:-

    <pre lang="javascript"> matches = 'ababababababa'.match(/[a]/g); alert(matches); alert(matches.length); </pre>

    Here's how to use modifiers with the RegExp object:-

    <pre lang="javascript"> alert(RegExp('[test]+','i').exec('TeSt')) </pre>

    Ok I hope you're following so far, I'm going to move onto replace now and how to use the various combinations.

    Here's how to use replace, notice how only one "t" is replaced:-

    <pre lang="javascript"> str = 'test'; alert(str.replace('t','x')) </pre>

    In order to match more than one instance of the string and use a regular expression you have to do the following:-

    <pre lang="javascript"> alert('test'.replace(/t/g,'x')) </pre>

    Javascript also supports anonymous functions within replace which is really powerful, you can even nest the replaces and perform other logic:-

    <pre lang="javascript"> alert('teeest'.replace(/e+/g, function(str) { return str.replace(/e/g,'x'); })); </pre>

    You can also use parenthesis with replace and match the subpatterns like this:-

    <pre lang="javascript"> alert('567'.replace(/([0-9])([0-9])([0-9])/,'$3$2$1')); </pre>

    That's all for now I may follow up this article at a later date when I have some spare time, I hope you enjoyed it.

    ← Back to articles