最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RegEx: different initials format - Stack Overflow

programmeradmin0浏览0评论

I am using this piece of code to get the initials of the person's full name:

var name = "John Smith"; // for an example
var initials = name.match(/\b\w/g) || [];
initials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
// initials then returns "JS"

Now I need my initials to return the first letter of the first name and three letters of the last name ("JSMI" in the example above).

What should I alter in my regex in order to do that?

Also, if person would have two names (for example "John Michael Smith"), I need to get "JMSMI" as a result...

Any other solutions are wele!

I am using this piece of code to get the initials of the person's full name:

var name = "John Smith"; // for an example
var initials = name.match(/\b\w/g) || [];
initials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();
// initials then returns "JS"

Now I need my initials to return the first letter of the first name and three letters of the last name ("JSMI" in the example above).

What should I alter in my regex in order to do that?

Also, if person would have two names (for example "John Michael Smith"), I need to get "JMSMI" as a result...

Any other solutions are wele!

Share Improve this question asked Apr 25, 2017 at 8:04 Gintas KGintas K 1,4783 gold badges18 silver badges39 bronze badges 11
  • what if last name is less than 3 letters? – tsh Commented Apr 25, 2017 at 8:07
  • @tsh I'm pretty sure there won't be any in my case, but ideally it should return the full last name then (1 or 2 letters) – Gintas K Commented Apr 25, 2017 at 8:09
  • "John Michael Smith" has three names, not two. – user663031 Commented Apr 25, 2017 at 8:10
  • @torazaburo I meant two first names :) – Gintas K Commented Apr 25, 2017 at 8:11
  • Try var res = name.match(/\b\w{1,3}(?=\w*$)|\b\w/g).map(x => x.toUpperCase()).join(""); – Wiktor Stribiżew Commented Apr 25, 2017 at 8:11
 |  Show 6 more ments

6 Answers 6

Reset to default 3

Try with Array#split() , substring() and Array#map

  1. first you need split the string with space.
  2. And get the single letter array[n-1] using sustring,
  3. Then get the 3 letter on final argument of array
  4. Map function iterate each word of your string

function reduce(a){
var c= a.split(" ");
var res = c.map((a,b) => b < c.length-1 ? a.substring(0,1) : a.substring(0,3))
return res.join("").toUpperCase()
}

console.log(reduce('John Michael Smith'))
console.log(reduce('John Smith'))

You may add a \b\w{1,3}(?=\w*$) alternative to your existing regex at the start to match 1 to 3 words chars in the last word of the string.

var name = "John Michael Smith"; //John Smith" => JSMI
var res = name.match(/\b\w{1,3}(?=\w*$)|\b\w/g).map(function (x) {return x.toUpperCase()}).join("");
console.log(res);

See the regex demo.

Regex details:

  • \b - a leading word boundary
  • \w{1,3} - 1 to 3 word chars (ASCII letters, digits or _)
  • (?=\w*$) - a positive lookahead requiring 0+ word chars followed with the end of string position
  • | - or
  • \b\w - a word char at the start of a word.

I tried to avoid capturing groups (and used the positive lookahead) to make the JS code necessary to post-process the results shorter.

Use split() and substr() to easily do this.

EDIT

Updated code to reflect the middle initial etc

function get_initials(name) {
  var parts = name.split(" ");

  var initials = "";
  for (var i = 0; i < parts.length; i++) {
    if (i < (parts.length - 1)) {
      initials += parts[i].substr(0, 1);
    } else {
      initials += parts[i].substr(0, 3);
    }
  }
  return initials.toUpperCase();

}

console.log(get_initials("John Michael Smith"));

You may want use String.prototype.replace to drop following letters:

This regexp will match first 1 (or 3 for last name) letters in a word, and only keep it.

'John Smith'.replace(/(?:(\w)\w*\s+)|(?:(\w{3})\w*$)/g, '$1$2').toUpperCase()

My two cents with a reducer :)

function initials(name) {
  return name.split(' ').reduce(function(acc, item, index, array) {
    var chars = index === array.length - 1 ? 3 : 1;
    acc += item.substr(0, chars).toUpperCase();
    return acc;
  }, '')
}

console.log(initials('John'));
console.log(initials('John Michael'));
console.log(initials('John Michael Smith'));

const name = "John Michael Smith";

const initials = name.toUpperCase().split(/\s+/)
  .map((x, i, arr) => x.substr(0, i === arr.length - 1 ? 3 : 1))
  .join('');

console.log(initials);

发布评论

评论列表(0)

  1. 暂无评论