Puyup
Puyup

Reputation: 43

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

Upvotes: 2

Views: 1375

Answers (4)

Code Maniac
Code Maniac

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 alphabet

let str = 'BZ8345LK'

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

console.log(op)

Upvotes: 6

Yves Kipondo
Yves Kipondo

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

nanndoj
nanndoj

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

CertainPerformance
CertainPerformance

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

Related Questions