Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex add space in string if the word is longer than 4 characters and have numbers

I try to create a regex with 2 condition:

  • if word length more than 4 character
  • And if the word contains numbers

I need to add spaces

So like: iph12 return iph12, but iphone12 return iphone 12

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wrote regex

.replace(/\d+/gi, ' $& ').trim()

and this function return in anyway string like iphone 12. I tried to use function

.replace(/(?=[A-Z]+\d|\d+[A-Z])[A-Z\d]{,4}/i, ' $& ').trim()

but without second argument in {,4} it’s not working. So is this possible?

>Solution :

You can use

text.replace(/\b([a-zA-Z]{4,})(\d+)\b/g, '$1 $2')

See the regex demo. Details:

  • \b – word boundary
  • ([a-zA-Z]{4,}) – Group 1: four or more ASCII letters
  • (\d+) – Group 2: one or more digits
  • \b – word boundary

See the JavaScript demo:

const texts = ['iphone12', 'iph12'];
const regex = /\b([a-zA-Z]{4,})(\d+)\b/g;
for (const text of texts) {
    console.log(text, '=>', text.replace(regex, '$1 $2'));
}

Output:

iphone12 => iphone 12
iph12 => iph12
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading