hugger
hugger

Reputation: 488

JS Regex for first letters only, but if the word it only two letters keep both AND numbers as is

Good day,

Is there a way to have a regex that works like so:

Say the word is, 79 Banana AK

I would want the result to be 79BAK

So Lemon 99 B3 would be L99B3

I've been playing around and managed to implement a regex that gets the first letters and keeps the full length of the number, but I can't figure out how to maintain the two letter words...

Here is the regex I currently have: let initials = title.match(/\b([a-zA-Z]|\d+)/g);

I hope this makes sense! Appreciate the help.

Upvotes: 2

Views: 74

Answers (1)

anubhava
anubhava

Reputation: 785126

You may use this replaceAll with 3 alternations:

str = str.replace(/\b(\d+\b|\w{2}\b|\w)\w*\b */g, "$1");

Code:

var arr = ['79 Banana AK', 'Lemon 99 B3']
var re = /\b(\d+\b|\w{2}\b|\w)\w*\b */g

arr.forEach(function(str) {
  console.log(str.replace(re, "$1"))
})

RegEx Demo

We match word boundary first then looks for all digits or just 2 characters words or else just first char of a word.

Upvotes: 3

Related Questions