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
1

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

5 Comments

This best choice in dynamic text input like on change.
Can you force remove extra space in number BZ 83 45 LK to BZ 8345 LK
If number format BZ83 45LK, how to keep output BZ 8345 LK
@Puyup First strip out the spaces then use the answer.
@Puyup you can simply remove all the space str.replace(/\s+/g,'')
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, '$& '));

1 Comment

If used in text input with onChange this code add more extra space each char and number.
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)

Comments

0

Try with this

var str = "BZ8345LK";
var result = str.replace(/([A-Z]+)(\d+)([A-Z]+)/, "$1 $2 $3");
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.