Return First Character of each word in a string

15,190

Solution 1

I would suggest you to use RegExp, Here's an Example

var myStr = "John P White";
var matches = myStr.match(/\b(\w)/g);
console.log(matches.join(''));

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

1st Capturing Group (\w)

\w matches any word character (equal to [a-zA-Z0-9_])

Global pattern flags

g modifier: global. All matches (don't return after first match)

For better explanation visit here

Solution 2

var name = "John P White";

function initials(value){
    var result = "";
    var tokens = value.split(/\s/);
    for(var i =0; i < tokens.length; i++){
      result += tokens[i].substring(0,1).toUpperCase();
    }
    return result;
}

initials(name);

Solution 3

You can do:

var words = $('a').text().split(' ');
var text = '';
$.each(words, function () {
    text +=  this.substring(0, 1);
});
$('a').text(text);

Fiddle Demo

Solution 4

You can do the following:

var name = "John P White",
    data = name.split(' '), output = "";

for ( var i = 0; i < data.length; i++) {
    output += data[i].substring(0,1);
}

alert(output);

Demo

Share:
15,190
Redwall
Author by

Redwall

Updated on June 11, 2022

Comments

  • Redwall
    Redwall almost 2 years

    I have a string with Names and I want to convert them to Initials. E.g:

    • John White -> JW
    • John P White -> JPW

    I am looking for a suggesting on how best to do this. I have researched using split() and looked here http://www.w3schools.com/jsref/jsref_split.asp but could not find a good example of how to target and return first letter when I don't know the char to look for.

    My string looks like this

    <a href="#">John White</a>
    

    and I want to change to this

    <a href="#">JW</a>
    

    Any help? Thanks

  • David Addoteye
    David Addoteye about 8 years
    I think this is the best answer.. It handles hyphenated words
  • phazei
    phazei over 6 years
    this breaks for names with a apostrophe or a hyphen
  • Tan Kucukhas
    Tan Kucukhas almost 2 years
    how can we limit this to return only 2 characters?