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

Time:12-15

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

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?

CodePudding user response:

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
  • Related