Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Add space between Char and Number with Regex

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
like image 396
Puyup Avatar asked Nov 22 '25 11:11

Puyup


2 Answers

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)
like image 57
Code Maniac Avatar answered Nov 24 '25 01:11

Code Maniac


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, '$& '));
like image 45
CertainPerformance Avatar answered Nov 23 '25 23:11

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!