Reputation: 43
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
Upvotes: 2
Views: 1375
Reputation: 37755
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 alphabetlet str = 'BZ8345LK'
let op = str.replace(/[a-z](?=\d)|\d(?=[a-z])/gi, '$& ')
console.log(op)
Upvotes: 6
Reputation: 5603
Try with this
var str = "BZ8345LK";
var result = str.replace(/([A-Z]+)(\d+)([A-Z]+)/, "$1 $2 $3");
console.log(result);
Upvotes: 0
Reputation: 6770
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)
Upvotes: 0
Reputation: 370729
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, '$& '));
Upvotes: 2