I want a regex that will select all characters including special characters, except the Last 4 Characters. Vanilla JS

Viewed 177
let str = "AAAAA-0000021111-1111"; 
let res = str.match(/\d(?=\d{4})/g);
document.write(res);

//This didnt work, the output is given below:

Output: 0,0,0,0,0,2

// its only selecting these characters which are highlighted in bold AAAAA-0000021111-1111

And this is what I am expecting:

A,A,A,A,A,-,0,0,0,0,0,2,1,1,1,1,-

Basically, I want all characters to be selected including - or any other special characters except the last 4.

I am listing a couple of extra samples for a better understanding

Sample1: ABC-101010-1111 Expected output is: A,B,C,-,1,0,1,0,1,0,-

Sample2: ABCD101010-11111 Expected output is: A,B,C,D,1,0,1,0,1,0,-,1

I am using Vanilla JS.

Really appreciate your involvement in this.

Thanks in Advance Sir/Ma'am!!!

1 Answers

You can use

/(?!\d{1,4}$)./g

See the regex demo.

NOTE: If you need to match all chars except last four any chars, you will need to replace \d with . in the lookahead, and it can be even written in a bit more succint way:

/.(?!.{0,3}$)/g

See this regex demo.

Details:

  • . - any single char other than line break char
  • (?!.{0,3}$) - a negative lookahead that matches a location not immediately followed with zero to three chars other than line break chars, till end of string.

The regex will match any char other than a line break char (., to match line breaks, use [^], [\s\S]/[\d\D]/[\w\W] or add s flag) that does not start a sequence of one, two, three or four digits at the end of string ((?!\d{1,4}$)).

See a JavaScript demo:

console.log("AAAAA-0000021111-1111".match(/(?!\d{1,4}$)./g))
console.log("AAAAA-0000021111-1111".match(/.(?!.{0,3}$)/g))

Related