2

Hello I have a plate number BZ8345LK and want convert to BZ 8345 LK (adding space between char and number).

I tried with this Regex but not working, only space first char with number. Ex BZ 8345LK, the 'LK' keep not space with number.

var str = 'BZ8345LK';
str.replace(/[^0-9](?=[0-9])/g, '$& ');
# return BZ 8345LK, I want BZ 8345 LK
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Puyup
  • 43
  • 7
  • here is explained why https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript – GrafiCode May 31 '19 at 09:34

4 Answers4

6

You can use this regex

[a-z](?=\d)|\d(?=[a-z])
  • [a-z](?=\d) - Match any alphabet followed by digit
  • | - Alternation same as logical OR
  • \d(?=[a-z]) - Any digit followed by alphabet

let str = 'BZ8345LK'

let op = str.replace(/[a-z](?=\d)|\d(?=[a-z])/gi, '$& ')

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
2

You should alternate with the other possibility, that a number is followed by a non-number:

var str = 'BZ8345LK';
console.log(str.replace(/[^0-9](?=[0-9])|[0-9](?=[^0-9])/g, '$& '));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • If used in text input with onChange this code add more extra space each char and number. – Puyup May 31 '19 at 09:40
0

An anoher option is to use:

^[^\d]+|[\d]{4}

Search for any not numeric character [^\d] followed by 4 numeric [\d]{4} characters

const str = 'BZ8345LK'
let answer = str.replace(/^[^\d]+|[\d]{4}/gi, '$& ')
console.log(answer)
nanndoj
  • 6,580
  • 7
  • 30
  • 42
0

Try with this

var str = "BZ8345LK";
var result = str.replace(/([A-Z]+)(\d+)([A-Z]+)/, "$1 $2 $3");
console.log(result);
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31