Search code examples
javascriptregexpostal-code

How to get 4 sequetial numbers for postcode in javascript from a string?


I am trying to figure out how to get 4 sequential numbers from a string which will be a postcode from the string. The regex seems to work fine in regex 101 but when I try to use it in javascript I get an error that reads Uncaught SyntaxError: Unexpected token ?

My code is

var str = "1 George Road, Sydney  NSW 2000"; 
console.log(str.match(((?<!\d)(\d{4}(\d{4})?)\b)));

Solution

  • You must include //g on regex for example /Your Pattern/g

    var str = "1 George Road, Sydney  NSW 2000"; 
    console.log(str.match(/((?<!\d)(\d{4}(\d{4})?)\b)/g));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>