0

I'm looking for some assistance with JavaScript/Regex when trying to format a string of text. I have the following IDs:

00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12

I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.

Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.

Sebastian Lenartowicz
  • 4,340
  • 4
  • 24
  • 36
McDuff
  • 27
  • 1
  • 6

4 Answers4

2

You could seach for leading digits and a following letter.

var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
    regex = /^\d*[a-z]/gi;

data.forEach(s => console.log(s.replace(regex, '')));

Or you could use String#slice for the last 8 characters.

var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];

data.forEach(s => console.log(s.slice(-8)));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
2

Instead of focussing on what you want to strip, look at what you want to get:

/\d{4}\/[A-Z]{1,2}\d{2}/

var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
trincot
  • 211,288
  • 25
  • 175
  • 211
0

A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in

[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})

var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");

input.forEach(function(x){
    console.log(re.exec(x)[1])
});
Jamiec
  • 118,012
  • 12
  • 125
  • 175
0

You could use this function. Using regex find the first letter, then make a substring starting after that index.

function getCode(s){
  var firstChar = s.match('[a-zA-Z]');
  return s.substr(s.indexOf(firstChar)+1)
}

getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
James
  • 3,523
  • 15
  • 30