Return initial letters of postcode in javascript

Viewed 71

How can I get the initial letters from a postcode in javascript? I just want the letters before the numbers start, like this:

E.g - 'L159XU' would return 'L'
E.g - 'TW136PZ' would return 'TW'

I was originally doing this:

const letters = postcode.substring(0, 2);

But some only have one letter, while others have two. Is there a way to do this?

5 Answers

I have tested this: HTML

<p id="test"></p>

JavaScript Regular Expressions

let text = 'TW136PZ';
let pattern = /[a-zA-Z]+|[0-9]+/g;
let result = text.match(pattern);

document.getElementById("test").innerHTML = result[0]; // return "TW"

use a split function with a regex,

let res = "TW136PZ".split(/[0-9]+/)[0] ; // TW

more about regex here

   

const postc='TwA1234';

const letters=postc.match( /^[a-zA-Z]+/ )[0];

console.log(letters);

^ – begin of input

a-z – lowercase English Letters included

A-Z – Uppercases included

+ – one or more times it appears!

As you wanted, it returns a string of as many initial latin latters as needed, three in this case.

There are different valid implementations

function callX() {
    return 'TW136PZ'.slice(0, 'TW136PZ'.search(/[0-9]/))
}
function callY() {
    return 'TW136PZ'.split(/[0-9]+/)[0]
}
function callZ() {
    return 'TW136PZ'.match( /^[a-zA-Z]+/ )[0]
}

when benchmarking these:

performance.mark("beginX");
for (let i = 0; i < 10000000; ++i) {
    callX();
}
performance.mark("endX");

performance.mark("beginY");
for (let i = 0; i < 10000000; ++i) {
    callY();
}
performance.mark("endY");

performance.mark("beginZ");
for (let i = 0; i < 10000000; ++i) {
    callZ();
}
performance.mark("endZ");

performance.measure("X","beginX","endX");
performance.measure("Y","beginY","endY");
performance.measure("Z","beginZ","endZ");

console.log(performance.getEntriesByType("measure"))

it turns out the first implementation is the fastest, while the second implementation (using split) is the slowest. I think this is due to not requiring to instantiate another array.

Posting a solution that does not use regular expressions, because I haven't seen one:

function parsePostcode(postcode) {
    const charIsADigit = function(ch) {
        const code = ch.charCodeAt(0)

        return code >= 48 && 58 > code;
    };

    let prefix = ""

    for (let i = 0; i < postcode.length; ++i) {
        const ch = postcode[i]
        const is_digit = charIsADigit(ch)

        if (is_digit) break;

        prefix += ch
    }

    return prefix;
}

console.log(parsePostcode("L159XU"))
console.log(parsePostcode("TW136PZ"))
Related