Taking the first letter of each word

How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?

Input: "Java Script Object Notation"

Output: "JSON"

Penny Liu's user avatar

Penny Liu

14.5k5 gold badges77 silver badges93 bronze badges

asked Nov 26, 2011 at 16:32

Gerben Jacobs's user avatar

Gerben JacobsGerben Jacobs

4,4753 gold badges33 silver badges54 bronze badges

I think what you’re looking for is the acronym of a supplied string.

var str = "Java Script Object Notation";
var matches = str.match(/b(w)/g); // ['J','S','O','N']
var acronym = matches.join(''); // JSON

console.log(acronym)

Note: this will fail for hyphenated/apostrophe’d words Help-me I'm Dieing will be HmImD. If that’s not what you want, the split on space, grab first letter approach might be what you want.

Here’s a quick example of that:

let str = "Java Script Object Notation";
let acronym = str.split(/s/).reduce((response,word)=> response+=word.slice(0,1),'')

console.log(acronym);

answered Nov 26, 2011 at 16:35

BotNet's user avatar

4

I think you can do this with

'Aa Bb'.match(/bw/g).join('')

Explanation: Obtain all /g the alphanumeric characters w that occur after a non-alphanumeric character (i.e: after a word boundary b), put them on an array with .match() and join everything in a single string .join('')


Depending on what you want to do you can also consider simply selecting all the uppercase characters:

'JavaScript Object Notation'.match(/[A-Z]/g).join('')

answered Nov 26, 2011 at 16:36

hugomg's user avatar

hugomghugomg

67.8k24 gold badges160 silver badges246 bronze badges

4

Easiest way without regex

var abbr = "Java Script Object Notation".split(' ').map(function(item){return item[0]}).join('');

answered Apr 3, 2015 at 6:23

Almis's user avatar

AlmisAlmis

3,6192 gold badges26 silver badges58 bronze badges

This is made very simple with ES6

string.split(' ').map(i => i.charAt(0))               //Inherit case of each letter
string.split(' ').map(i => i.charAt(0)).toUpperCase() //Uppercase each letter
string.split(' ').map(i => i.charAt(0)).toLowerCase() //lowercase each letter

This ONLY works with spaces or whatever is defined in the .split(' ') method

ie, .split(', ') .split('; '), etc.

string.split(' ') .map(i => i.charAt(0)) .toString() .toUpperCase().split(',')

maxshuty's user avatar

maxshuty

9,30313 gold badges62 silver badges75 bronze badges

answered Oct 1, 2018 at 15:42

Aaron Taddiken's user avatar

2

To add to the great examples, you could do it like this in ES6

const x = "Java Script Object Notation".split(' ').map(x => x[0]).join('');
console.log(x);  // JSON

and this works too but please ignore it, I went a bit nuts here :-)

const [j,s,o,n] = "Java Script Object Notation".split(' ').map(x => x[0]);
console.log(`${j}${s}${o}${n}`);

answered May 16, 2017 at 21:51

Darryl Hebbes's user avatar

Darryl HebbesDarryl Hebbes

9581 gold badge9 silver badges15 bronze badges

@BotNet flaw:
i think i solved it after excruciating 3 days of regular expressions tutorials:

==> I’m a an animal

(used to catch m of I’m) because of the word boundary, it seems to work for me that way.

/(s|^)([a-z])/gi

answered Apr 15, 2017 at 13:51

tomersss2's user avatar

0

It’s important to trim the word before splitting it, otherwise, we’d lose some letters.

const getWordInitials = (word: string): string => {
  const bits = word.trim().split(' ');
  return bits
    .map((bit) => bit.charAt(0))
    .join('')
    .toUpperCase();
};

$ getWordInitials("Java Script Object Notation")

$ «JSON»

answered May 27, 2022 at 10:24

exaucae's user avatar

exaucaeexaucae

1,7651 gold badge11 silver badges23 bronze badges

Try —

var text = '';
var arr = "Java Script Object Notation".split(' ');
for(i=0;i<arr.length;i++) {
    text += arr[i].substr(0,1)
}    
alert(text);

Demo — http://jsfiddle.net/r2maQ/

answered Nov 26, 2011 at 16:37

ipr101's user avatar

ipr101ipr101

24k7 gold badges58 silver badges61 bronze badges

Using map (from functional programming)

'use strict';

function acronym(words)
{
    if (!words) { return ''; }

    var first_letter = function(x){ if (x) { return x[0]; } else { return ''; }};

    return words.split(' ').map(first_letter).join('');
}

answered Dec 8, 2015 at 11:26

Ben Sarah Golightly's user avatar

Alternative 1:

you can also use this regex to return an array of the first letter of every word

/(?<=(s|^))[a-z]/gi

(?<=(s|^)) is called positive lookbehind which make sure the element in our search pattern is preceded by (s|^).


so, for your case:

// in case the input is lowercase & there's a word with apostrophe

const toAbbr = (str) => {
  return str.match(/(?<=(s|^))[a-z]/gi)
            .join('')
            .toUpperCase();
};

toAbbr("java script object notation"); //result JSON

(by the way, there are also negative lookbehind, positive lookahead, negative lookahead, if you want to learn more)


Alternative 2:

match all the words and use replace() method to replace them with the first letter of each word and ignore the space (the method will not mutate your original string)

// in case the input is lowercase & there's a word with apostrophe    

const toAbbr = (str) => {
  return str.replace(/(S+)(s*)/gi, (match, p1, p2) => p1[0].toUpperCase());
};

toAbbr("java script object notation"); //result JSON

// word = not space = S+ = p1 (p1 is the first pattern)
// space = s* = p2 (p2 is the second pattern)

answered Jul 21, 2018 at 14:42

Fatma Nabilla's user avatar

Fatma NabillaFatma Nabilla

1,2711 gold badge9 silver badges7 bronze badges

How about this:

var str = "", abbr = "";
str = "Java Script Object Notation";
str = str.split(' ');
for (i = 0; i < str.length; i++) {
    abbr += str[i].substr(0,1);
}
alert(abbr);

Working Example.

answered Nov 26, 2011 at 16:36

Madara's Ghost's user avatar

Madara’s GhostMadara’s Ghost

171k50 gold badges264 silver badges309 bronze badges

1

If you came here looking for how to do this that supports non-BMP characters that use surrogate pairs:

initials = str.split(' ')
              .map(s => String.fromCodePoint(s.codePointAt(0) || '').toUpperCase())
              .join('');

Works in all modern browsers with no polyfills (not IE though)

answered Jun 4, 2020 at 10:30

James's user avatar

JamesJames

24.4k13 gold badges82 silver badges129 bronze badges

Getting first letter of any Unicode word in JavaScript is now easy with the ECMAScript 2018 standard:

/(?<!p{L}p{M}*)p{L}/gu

This regex finds any Unicode letter (see the last p{L}) that is not preceded with any other letter that can optionally have diacritic symbols (see the (?<!p{L}p{M}*) negative lookbehind where p{M}* matches 0 or more diacritic chars). Note that u flag is compulsory here for the Unicode property classes (like p{L}) to work correctly.

To emulate a fully Unicode-aware b, you’d need to add a digit matching pattern and connector punctuation:

/(?<!p{L}p{M}*|[p{N}p{Pc}])p{L}/gu

It works in Chrome, Firefox (since June 30, 2020), Node.js, and the majority of other environments (see the compatibility matrix here), for any natural language including Arabic.

Quick test:

const regex = /(?<!p{L}p{M}*)p{L}/gu;
const string = "Żerard Łyżwiński";
// Extracting
console.log(string.match(regex));                        // => [ "Ż", "Ł" ]
// Extracting and concatenating into string
console.log(string.match(regex).join(""))                // => ŻŁ
// Removing
console.log(string.replace(regex, ""))                   // => erard yżwiński
// Enclosing (wrapping) with a tag
console.log(string.replace(regex, "<span>$&</span>"))    // => <span>Ż</span>erard <span>Ł</span>yżwiński

console.log("_Łukasz 1Żukowski".match(/(?<!p{L}p{M}*|[p{N}p{Pc}])p{L}/gu)); // => null

answered Jul 3, 2020 at 12:21

Wiktor Stribiżew's user avatar

Wiktor StribiżewWiktor Stribiżew

601k37 gold badges427 silver badges539 bronze badges

In ES6:

function getFirstCharacters(str) {
  let result = [];

  str.split(' ').map(word => word.charAt(0) != '' ? result.push(word.charAt(0)) : '');
  
  return result;
}

const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World    !!";

console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));

Output:

[ ‘H’, ‘W’, ‘1’, ‘!’ ]

[ ‘1’, ‘4’, ‘a’, ‘7’ ]

[ ‘H’, ‘W’, ‘!’ ]

Dharman's user avatar

Dharman

29.9k22 gold badges82 silver badges132 bronze badges

answered Nov 5, 2021 at 8:02

Sinh Nguyễn Đức's user avatar

This should do it.

var s = "Java Script Object Notation",
    a = s.split(' '),
    l = a.length,
    i = 0,
    n = "";

for (; i < l; ++i)
{
    n += a[i].charAt(0);
}

console.log(n);

dyoo's user avatar

dyoo

11.7k1 gold badge33 silver badges44 bronze badges

answered Nov 26, 2011 at 16:36

JesseBuesking's user avatar

JesseBueskingJesseBuesking

6,4584 gold badges43 silver badges89 bronze badges

The regular expression versions for JavaScript is not compatible with Unicode on older than ECMAScript 6, so for those who want to support characters such as «å» will need to rely on non-regex versions of scripts.

Event when on version 6, you need to indicate Unicode with u.

More details: https://mathiasbynens.be/notes/es6-unicode-regex

answered Oct 22, 2015 at 13:56

SondreB's user avatar

SondreBSondreB

7986 silver badges14 bronze badges

Yet another option using reduce function:

var value = "Java Script Object Notation";

var result = value.split(' ').reduce(function(previous, current){
    return {v : previous.v + current[0]};
},{v:""});


$("#output").text(result.v);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output"/>

answered May 18, 2016 at 8:01

Vadim Gremyachev's user avatar

Vadim GremyachevVadim Gremyachev

57.4k20 gold badges129 silver badges191 bronze badges

This is similar to others, but (IMHO) a tad easier to read:

const getAcronym = title =>
  title.split(' ')
    .map(word => word[0])
    .join('');

answered Sep 20, 2019 at 12:12

ihake's user avatar

ihakeihake

1,7311 gold badge17 silver badges29 bronze badges

ES6 reduce way:

const initials = inputStr.split(' ').reduce((result, currentWord) => 
    result + currentWord.charAt(0).toUpperCase(), '');
alert(initials);

answered Jan 16, 2020 at 9:34

user3818229's user avatar

user3818229user3818229

1,4972 gold badges19 silver badges44 bronze badges

Try This Function

const createUserName = function (name) {
const username = name
    .toLowerCase()
    .split(' ')
    .map((elem) => elem[0])
    .join('');

    return username;
};

console.log(createUserName('Anisul Haque Bhuiyan'));

answered Mar 1, 2022 at 1:32

String str is given which contains lowercase English letters and spaces. It may contain multiple spaces. Get the first letter of every word and return the result as a string. The result should not contain any space.

Examples: 

Input : str = "geeks for geeks"
Output : gfg

Input : str = "geeks for geeks""
Output : hc

Source: https://www.geeksforgeeks.org/amazon-interview-set-8-2/

The idea is to traverse each character of string str and maintain a boolean variable, which was initially set as true. Whenever we encounter space we set the boolean variable is true. And if we encounter any character other than space, we will check the boolean variable, if it was set as true as copy that charter to the output string and set the boolean variable as false. If the boolean variable is set false, do nothing. 

Algorithm: 

1. Traverse string str. And initialize a variable v as true.
2. If str[i] == ' '. Set v as true.
3. If str[i] != ' '. Check if v is true or not.
   a) If true, copy str[i] to output string and set v as false.
   b) If false, do nothing.

Implementation:

C++

#include<bits/stdc++.h>

using namespace std;

string firstLetterWord(string str)

{

    string result = "";

    bool v = true;

    for (int i=0; i<str.length(); i++)

    {

        if (str[i] == ' ')

            v = true;

        else if (str[i] != ' ' && v == true)

        {

            result.push_back(str[i]);

            v = false;

        }

    }

    return result;

}

int main()

{

    string str = "geeks for geeks";

    cout << firstLetterWord(str);

    return 0;

}

Java

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        boolean v = true;

        for (int i = 0; i < str.length(); i++)

        {

            if (str.charAt(i) == ' ')

            {

                v = true;

            }

            else if (str.charAt(i) != ' ' && v == true)

            {

                result += (str.charAt(i));

                v = false;

            }

        }

        return result;

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        System.out.println(firstLetterWord(str));

    }

}

Python 3

def firstLetterWord(str):

    result = ""

    v = True

    for i in range(len(str)):

        if (str[i] == ' '):

            v = True

        elif (str[i] != ' ' and v == True):

            result += (str[i])

            v = False

    return result

if __name__ == "__main__":

    str = "geeks for geeks"

    print(firstLetterWord(str))

C#

using System;

class GFG

{

    static String firstLetterWord(String str)

    {

        String result = "";

        bool v = true;

        for (int i = 0; i < str.Length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    public static void Main()

    {

        String str = "geeks for geeks";

        Console.WriteLine(firstLetterWord(str));

    }

}

Javascript

<script>

    function firstLetterWord(str)

    {

        let result = "";

        let v = true;

        for (let i = 0; i < str.length; i++)

        {

            if (str[i] == ' ')

            {

                v = true;

            }

            else if (str[i] != ' ' && v == true)

            {

                result += (str[i]);

                v = false;

            }

        }

        return result;

    }

    let str = "geeks for geeks";

      document.write(firstLetterWord(str));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 1 : Reverse Iterative Approach 

This is simplest approach to to getting first letter of every word of the string. In this approach we are using reverse iterative loop to get letter of words. If particular letter ( i ) is 1st letter of word or not is can be determined by checking pervious character that is (i-1). If the pervious letter is space (‘ ‘) that means (i+1) is 1st letter then we simply add that letter to the string. Except character at 0th position. At the end we simply reverse the string and function will return string which contain 1st letter of word of the string.

C++

#include <iostream>

using namespace std;

void get(string s)

{

    string str = "", temp = "";

    for (int i = s.length() - 1; i > 0; i--) {

        if (isalpha(s[i]) && s[i - 1] == ' ') {

            temp += s[i];

        }

    }

    str += s[0];

    for (int i = temp.length() - 1; i >= 0; i--) {

        str += temp[i];

    }

    cout << str << endl;

}

int main()

{

    string str = "geeks for geeks";

    string str2 = "Code of the    Day";

    get(str);

    get(str2);

    return 0;

}

Java

public class GFG {

    public static void get(String s)

    {

        String str = "", temp = "";

        for (int i = s.length() - 1; i > 0; i--) {

            if (Character.isLetter(s.charAt(i))

                && s.charAt(i - 1) == ' ') {

                temp

                    += s.charAt(i);

            }

        }

        str += s.charAt(0);

        for (int i = temp.length() - 1; i >= 0; i--) {

            str += temp.charAt(i);

        }

        System.out.println(str);

    }

    public static void main(String[] args)

    {

        String str = "geeks for geeks";

        String str2 = "Code of the    Day";

        get(str);

        get(str2);

    }

}

Python3

def get(s):

    str = ""

    temp = ""

    for i in range(len(s)-1, 0, -1):

        if s[i].isalpha() and s[i-1] == ' ':

            temp += s[i]

    str += s[0]

    for i in range(len(temp)-1, -1, -1):

        str += temp[i]

    print(str)

str = "geeks for geeks"

str2 = "Code of the    Day"

get(str)

get(str2)

Javascript

function get(s) {

  let str = "", temp = "";

  for (let i = s.length - 1; i > 0; i--) {

    if (s[i].match(/[a-zA-Z]/) && s[i - 1] === ' ') {

      temp += s[i];

    }

  }

  str += s[0];

  for (let i = temp.length - 1; i >= 0; i--) {

    str += temp[i];

  }

  console.log(str);

}

const str = "geeks for geeks";

const str2 = "Code of the    Day";

get(str);

get(str2);

Time Complexity: O(n)
Auxiliary space: O(1). 

Approach 2: Using StringBuilder

This approach uses the StringBuilder class of Java. In this approach, we will first split the input string based on the spaces. The spaces in the strings can be matched using a regular expression. The split strings are stored in an array of strings. Then we can simply append the first character of each split string in the String Builder object.  

Implementation:

C++

#include <bits/stdc++.h>

using namespace std;

string processWords(char *input)

{

    char *p;

    vector<string> s;

    p = strtok(input, " ");

    while (p != NULL)

    {

        s.push_back(p);

        p = strtok(NULL, " ");

    }

    string charBuffer;

    for (string values : s)

        charBuffer += values[0];

    return charBuffer;

}

int main()

{

    char input[] = "geeks for geeks";

    cout << processWords(input);

    return 0;

}

Java

class GFG

{

   private static StringBuilder charBuffer = new StringBuilder();

   public static String processWords(String input)

   {

        String s[] = input.split("(\s)+");

        for(String values : s)

        {

            charBuffer.append(values.charAt(0));

        }

      return charBuffer.toString();

   }

   public static void main (String[] args)

   {

      String input = "geeks for geeks";

      System.out.println(processWords(input));

   }

}

Python3

charBuffer = []

def processWords(input):

    s = input.split(" ")

    for values in s:

        charBuffer.append(values[0])

    return charBuffer

if __name__ == '__main__':

    input = "geeks for geeks"

    print(*processWords(input), sep = "")

C#

using System;

using System.Text;

class GFG

{

private static StringBuilder charBuffer = new StringBuilder();

public static String processWords(String input)

{

        String []s = input.Split(' ');

        foreach(String values in s)

        {

            charBuffer.Append(values[0]);

        }

    return charBuffer.ToString();

}

public static void Main()

{

    String input = "geeks for geeks";

    Console.WriteLine(processWords(input));

}

}

Javascript

<script>

var charBuffer = "";

function processWords(input)

{

        var s = input.split(' ');

        s.forEach(element => {

            charBuffer+=element[0];

        });

    return charBuffer;

}

var input = "geeks for geeks";

document.write( processWords(input));

</script>

Time Complexity: O(n)
Auxiliary space: O(1). 

Another Approach: Using boundary checker, refer https://www.geeksforgeeks.org/get-first-letter-word-string-using-regex-java/

This article is contributed by Aarti_Rathi and Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

The metacharacter “b” matches for the word boundaries and [a-zA-Z] matches one character from the English alphabet (both cases). In short, the expression b[a-zA-Z] matches one single character from the English alphabet, both cases after every word boundary.

Therefore, to retrieve the first letter of each word −

  • Compile the above expression of the compile() method of the Pattern class.

  • Get the Matcher object bypassing the required input string as a parameter to the matcher() method of the Pattern class.

  • Finally, for each match get the matched characters by invoking the group() method.

Example

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "b[a-zA-Z]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("First letter of each word from the given string: ");
      while(matcher.find()) {
         System.out.print(matcher.group()+" ");
      }
   }
}

Output

Enter sample text:
National Intelligence Agency Research & Analysis Wing
First letter of each word from the given string:
N I A R A W

Member Avatar

14 Years Ago

Hey all!

I’m new to programming so please be patient if my question is obvious or listed somewhere else (I’ve looked!)

I want to be able to enter a sentence, split the sentence into septate words and then take the first letter of each word to create a new string. So that:
«the brown fox»
returns:
«tbf»

So far all I can do is split the sentence into the separate words:

import string
def main():
    print "This program splits the words in a sentence"
    print
    p = raw_input("Enter a sentence: ")
    words = string.split(p)
    print "The split words are:", words
    
main()

Thanks for any help!


Recommended Answers

I give you two versions so that you can compare them

def firstLettersA(theString):
    theWords = theString.split()
    theLetters = mapl(lamda w: w[:1], theWords)
    theResult = ''.join(theLetters)
    print theWords, theLetters, theResult
    return theResult

def firstLettersB(theString):
    return ''.join(map(lambda w: w[:1], theString.split()))

def main():
    print "This program splits the words in …

Jump to Post

All 4 Replies

Member Avatar


Gribouillis

1,391



Programming Explorer



Team Colleague


14 Years Ago

I give you two versions so that you can compare them

def firstLettersA(theString):
    theWords = theString.split()
    theLetters = mapl(lamda w: w[:1], theWords)
    theResult = ''.join(theLetters)
    print theWords, theLetters, theResult
    return theResult

def firstLettersB(theString):
    return ''.join(map(lambda w: w[:1], theString.split()))

def main():
    print "This program splits the words in a sentence"
    print
    p = raw_input("Enter a sentence: ")
    print "The first letters are '%s'"  % firstLettersB(theString)

Member Avatar


jlm699

320



Veteran Poster


14 Years Ago

Here’s one making use of list comprehension:

>>> def FirstLetters( s ):
...     return ''.join( [ lett[0] for lett in s.split() ] )
...     
>>> FirstLetters( 'My mother used to bake apple pies in the foo bar' )
'Mmutbapitfb'
>>>

Member Avatar

14 Years Ago

If list comprehension or generator expressions are not in your knowledge yet, maybe this is a little easier to understand:

def first_letters(s):
    temp = ""
    for letter in s.split():
        temp += letter[0]
    return temp
    
s = 'Old hero sleeps healthy in Thailand'
print first_letters(s)

A little bit more long winded, but using only very basic concepts:

def first_letters2(s):
    space = " "
    s = space + s
    temp = ""
    for k in range(len(s)):
        if s[k] == space:
            temp += s[k+1]
    return temp

s = 'My mother used to bake apple pies in the foo bar'
print first_letters2(s)

Member Avatar


Hogg

0



Newbie Poster


14 Years Ago

Thanks for the help guys!

The one that made the most sense to me was the first_letters2 code.

Again, thanks all for the help.


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

If you are looking for an array formula to extract the first letter of each word in Google Sheets, find two formulas below. Among them, one is very tricky and easy to use.

To extract the first letter of each word, we usually follow the below steps in Google Sheets (I won’t follow it to write the array formula).

Let’s assume cell A2 contains the string “medium weight beam“.

I want to extract the letters “m”, “w”, and “b” and join them as an abbreviation like “mwb“.

Usually, we will solve the above problem USING SPLIT, LEFT, and JOIN as below and drag it down to apply to the string in the next row.

Extract the First Letter of Each Word - Non Array

Steps (formula Explanation):-

1. We can use the SPLIT function to split the string into three parts based on the space delimiter.

=split(A2," ")

2. Then using the LEFT function, we can extract the first letter from each word.

=ArrayFormula(left(split(A2," "),1))

I’ve used the ArrayFormula within the above formula since we want to extract the first letter from more than one (split) word.

3. Just combine the result.

=JOIN("",ArrayFormula(left(split(A2," "),1)))

It is advisable to wrap the formula with IFERROR to avoid error incase of no values in A2.

The above is the best non-array method to extract the first letter of each word in Google Sheets.

But this formula has one problem.

Since we have used the JOIN function, we may find it difficult to code an array formula following the above method.

We can only use part of the formula that I’ll explain later.

Here I have two alternative solutions to the above problem. One is very tricky and easy to use than the above non-array one.

I’ve two formulas below titled Array Formula 1 and Array Formula 2.

I am recommending the array formula 1.

If you are not concerned about the case sensitivity of the extracted letters, use it. It is the easiest way to extract the first letter of each word in Google Sheets.

The Array Formula 1 will convert all the extracted letters to CAPS. If you want, you can make it SMALL (lower case).

Use the Array Formula 2 if you are looking for a case sensitive formula. I mean, the extracted letters will be the same as in the string. It won’t change the letters’ case.

Array Formula 1

Let’s consider the same string in cell A2, which is “medium weight beam”.

Here is the easiest way to abbreviate the above string in Google Sheets.

Steps:-

1. Use the PROPER function to make the first letter of each word capital and the rest of the letters small.

=proper(A2)

The result will be “Medium Weight Beam”.

2. Using REGEXREPLACE, we can extract only the capital letters from the above string.

=REGEXREPLACE(proper(A2),"[^A-Z]+","")

Since it doesn’t contain the JOIN function, we can easily make it an array formula.

=ArrayFormula(REGEXREPLACE(proper(A2:A),"[^A-Z]+",""))

Extract the First Letter of Each Word - Array Formula

Array Formula 2

To get one more array formula to extract the first letter of each word in Google Sheets, please follow the steps below.

Here, we will SPLIT the strings, then extract the first letter using LEFT. Instead of JOIN, we will use the QUERY to combine the extracted letters.

1. Let’s first FILTER the range A2:A to skip blank rows.

=filter(A2:A,A2:A<>"")

2. Split the filtered strings.

=ArrayFormula(split(filter(A2:A,A2:A<>"")," "))

Step 1 - Split Words

3. Let’s extract the first letter in each word.

=ArrayFormula(left(split(filter(A2:A,A2:A<>"")," "),1))

4. Using the QUERY, we can combine the extracted letters. I’ve got a detailed tutorial on the use of QUERY for joining strings here – The Flexible Array Formula to Join Columns in Google Sheets.

How it works?

We can use the HEADER of QUERY for this. We will use an arbitrarily large number in the header. So, the QUERY will consider all the rows in the range are headers and combine them into a single row.

4.1. Use TRANSPOSE to change the orientation of the above formula result.

=TRANSPOSE(ArrayFormula(left(split(filter(A2:A,A2:A<>"")," "),1)))

4.2. Use the QUERY to combine the letters.

=query(transpose(ArrayFormula(left(split(filter(A2:A,A2:A<>"")," "),1))),,9^9)

4.3. Again transpose it.

=transpose(query(transpose(ArrayFormula(left(split(filter(A2:A,A2:A<>"")," "),1))),,9^9))

Step 2 - Split Words and Query

The above is the array formula to extract the first letter from each word in Google Sheets.

But wait. See the results. The Query leaves white spaces between the joined letters.

You can use REGEXREPLACE or SUBSTITUTE to remove them.

=ArrayFormula(substitute(transpose(query(transpose(left(split(filter(A2:A,A2:A<>"")," "),1)),,9^9))," ",""))

Note:- If you have blank cells between the values in A2:A, use the below formula. In this formula, I have omitted the FILTER and included IFERROR after the SPLIT.

=ArrayFormula(substitute(transpose(query(transpose(left(iferror(split(A2:A," ")),1)),,9^9))," ",""))

I hope you could understand how to extract the first letter of each word in Google Sheets.

Thanks for the stay. Enjoy!

Понравилась статья? Поделить с друзьями:
  • Taking place another word
  • Taking pdf to word
  • Taking out a page in word
  • Taking notes in word
  • Taking images from word