Return The first character of each word in a string

I have a string with names and I want to convert them to Initials. For instance:

  • John White → JW
  • John P White → JPW

I am looking for suggestions on how best to do this. I 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 the first letter when I don’t know the char to search.

My line looks like

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

and I want to go to this

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

Any help? Thanks

+3
source share
7 answers

I suggest you use RegExp, here is an example

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

\b approve the position on the word boundary (^\w|\w$|\W\w|\w\W)

First capture group ( \w)

\w ( [a-zA-Z0-9_])

g : . ( )

+12

:

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

+1

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);

+1
source

With a separator, how spacecan you split the names and put them in an array. And then you can take the first index of each element inside the array.

0
source
"John P White".split(/\s+/g).reduce(function (previousValue, currentValue) {
    return previousValue + currentValue.charAt(0);
}, "");
// returns JPW
0
source
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);
0
source

You can use the regex to match any that is not uppercase, and then just delete it.

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

$('a').each(function(){
    var initials = $(this).text().replace(/[^A-Z]/g, "");
    $(this).text(initials);
});

fiddle

0
source

All Articles